Using static variables (or similar) to affect instances of the same object separately.

Hi everyone,

So basically, I’ve got an RPG world with many of the same item (let’s say it’s a rock). I’ve been using static variables to keep data about the player between scenes, but I’m not sure of the best practice to store information for specific instances of objects.

If I have 3 rocks I can go and collect, all with the same script, and I grab one of them, I can set a static bool to true for collecting it and it’ll keep that between scenes, but when I return, it’s set all instances to true (I guess because the static bool counts for all of them). I need a way to keep the data about which item instances specifically I’ve collected so that they a) wont respawn when I re-enter and b) I can save that data out eventually so they’ll never spawn again.

The only way I can think of is to have a huge list of individal instance item references for each individual item in the world (there will be 1000s over the game in total) and set them to true or false for either, but surely that’s not the best practice. Any help would be hugely appreciated.

Thanks in advance!

Static variables are persistent data, sharing between scenes. The purpose of a static variable within a class is to share it between all instances. A static variable is just a non instance variable, A great use for static variable and easy to understand is a count, you make a class with a static count when you create an instance you add to the count, when you destroy you remove from the count, any instance specific data can not be static. If you want your data to persist between scenes you don’t need it to be static. But what you should be looking into is scriptable objects for that, scriptable object data is persistent across scenes, they live in the project not the scene.

Thanks for your replies guys. I did look into serialising but couldn’t see how I’d serialise for individuals instances of objects. The same for scriptable objects.

I like the idea of using a count and adding on start, that’s not a bad shout.

In the end, I had it use the in world name for each, so when it soawns Rock (1) and then Rock (2) etc I can keep track. Then on spawn, it checks for if an item matching that name exists in the collected item list. If it does, to destroy it.

It seems to be working as it stands, at least.

Thanks for your help guys! :0