[SOLVED] List problem

I have spawn manager script which keeps a list of all objects that it spawns in a list. If a certain number of objects have already been spawned then it doesn’t spawn any more until other objects are destroyed. When a object is destroyed it is removed from the list and when a new object is spawned it is added to the list.

There is only one spawn manager object. I had a problem where the contents of the list would be lost and I couldn’t figure out why. I thought I would try making the list static and that fixed the problem but I don’t understand why. The list is only ever referenced from the same script that created it and no other scripts interact with it at all. I would have thought that it wouldn’t need to be static. I must have misunderstood how static objects work. Any advice as to why I had to make the list static is welcomed.

Doesn’t matter if list is static, or instantiated, as long is referenced accordingly.
You may need to study difference, between static and none static properties.

Without seeing your case example, is hard to figure out, where is your exact problem.

Thanks, I’ll read up on static objects and I’ll post my code if I still don’t understand what the problem was caused by.

You can share your code and perhaps we’ll be able to figure out why making your list static solved your issue.

Anyhow, the difference between static and non-static objects is very technical, but can be reduced to a simple explanation. We say an object can be static when there is only one instance of it. For example, you have many instances of your spawned objects, because you spawn them many times. This objects, then, can’t be static. But you have only one SpawnManager, and there’s no other SpawnManager in your game, and because of that this script (or its properties) can be static.

The benefits of making an a class/method static is that you don’t need to reference that class/method to call it, and that it saves a few lines of code (you don’t need to do the classic GetComponent and such…). The dangers of having static classes or methods is that they can be hard to debug in large projects and slightly more prone to error. I think that if you use them wisely -and not too much- they can be a great coding practice.

Thanks for your help I now know what was causing the problem.

Other objects call a method in the spawn manager e.g

public GameObject SpawnManager; //SpawnManager script reference in inspector
SpawnManager.GetComponent<SpawnManager>().method_spawn_objects(); //calling method

And each object that called this function a new instance of the spawn manager class would be created so the list was being created each time a new object called the method. By making the list static just one version of the list is used.

I’m still learning C# and it’s things like this that are good learning lessons.