Sign in to follow this  
Cunning fox

Need help with math.random

Recommended Posts

Cunning fox    706

So, I'm trying to add chance to drop item, when player dies. I've got following code:

local chadrop = math.random(1,2)


--Лут при смерти (даем в инвентарь).
AddStategraphPostInit("wilson", function(sg)
    local old_death_fn = sg.events.death.fn
	--if old_doattack==nil then p("fn nil!") end
    sg.events.death.fn = function(inst, data, ...)
		local h = inst.components.health
		local inv = inst.components.inventory
		if h == nil or inv == nil then
			return old_death_fn(inst, data, ...)
		end
		local r=h.restored

			if chadrop == 1 then
			local eye = SpawnPrefab("carrot")
			if eye then
				inv:GiveItem(eye)
			end
			elseif chadrop == 2 then
			local eye = SpawnPrefab("humanmeat")
			if eye then
				inv:GiveItem(eye)
			end
			
			end
	
		return old_death_fn(inst, data, ...)
    end
end)

It's working an droping item nicely, but math.random gives to "chadrop" number, and it exists untill the end of the game. How to make this, so it'll rewrite "chadrop" every time player dies?

Edited by makar5000
  • Like 1

Share this post


Link to post
Share on other sites
alainmcd    901

Your

local chadrop = math.random(1,2)

is outside the scope of sg.events.death.fn, so it's only executed once when loading your mod. Move that line to within the function, for example, right before:

if chadrop == 1 then

 

Share this post


Link to post
Share on other sites
Cunning fox    706
17 hours ago, alainmcd said:

Your


local chadrop = math.random(1,2)

is outside the scope of sg.events.death.fn, so it's only executed once when loading your mod. Move that line to within the function, for example, right before:


if chadrop == 1 then

 

Many thanks!

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this