- Home /
Populating a list with multiple GameObjects
Hello
My gameobject's are subscribed to an event that when called, passes the gameobject to a static method which takes care of disabling and hiding that gameobject. The static method also adds that gameobject to a list so I can keep track of the disabled gameobjects.
My question is when I call this static method on multiple objects at the same time.
1) How is the order to which they are added to the list decided?
2) Is a list the best way to keep track of them?
I'm thinking about storing the transform of the gameobject before it is disabled, so when I come to enable it I can set it back to it's previous position.
I will add that I haven't use static methods or variables often, but I would like to be able to see the list of gameobjects in the inspector. Since the method is static I made the list static, from my understanding of static variables that would make sense as I don't need multiple instances of this class( correct? ), but static variables don't show up in the inspector.
3) Should I make them non-static and create an instance of the class at start time?
Thanks
Answer by Philipp · Dec 11, 2012 at 05:57 PM
How do you call the method "on multiple objects at the same time"? Is the method called by events that are fired by Unity for multiple objects "at the same time" (such as OnBecameVisible, if several objects appear within the same frame)? If so, the order in which objects are added to the list is the order in which the events are fired, which I'd consider to be undefined.
Sure, a List is fine – unless you're dealing with vast amounts of objects, you're not going to find anything noticeably more efficient.
Consider making a Singleton of sorts: Have an instance of the class attached to a GameObject, but make the instance register itself as a static variable. Have a static method that returns this variable, and use that (rather than Find()) to access your instance.
Thanks for your reply I'll have to look into the Singleton design pattern.
Currently I'm just testing the way I have things, at the moment an event calls a method in a script attached to each gameobject; The event is fired via a GUI button, but later on will be fired by collision or other methods. $$anonymous$$ost of the time in my game multiple objects won't be added to the list at the same time, but there may be times when that happens such as some sort of AOE weapon.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
A node in a childnode? 1 Answer
Sort List by string field 1 Answer
C# NullReferenceException 1 Answer