#variable becoming null (state machine)

1 messages · Page 1 of 1 (latest)

mortal grove
#

So I have a code for an enemy that uses state machines. It is a coyote that is supposed to follow a sheep.
When it enters the "seeking" state it gets the body.global_position of the sheep (through the variable "sheep") and follows that direction until the sheep has been bitten (entering the "bite" state) or it goes out of sight (goes back to "wander" state)

Up to that point it works. but when the coyote actually enters the "bite" state (meaning it has come in contact with the sheep) the "sheep" variable becomes null and the "seeking" states breaks. I don't understand why this happens.

(adding image of the main code that triggers the states)
Let me know if you need more info

wicked star
#

That would set coyote.sheep to null, but I have another suggestion for how you might deal with this

#

In a case where you only ever have one of something, e.g a single player character or a scoreboard, you may be best using a Singleton. If there’s one sheep only, you can get the sheep to register itself with the singleton therefore everything can access it

Make a new script somewhere in your resources, call it something like GameData or something

Then go to project settings > AutoLoad and select your new script, this will add it as a singleton instance in your game

Then from anywhere you can access it, so you can store your sheep on it and get it from anywhere