- Home /
How to do this?
How could I get every game object that has a certain script and than effect that game object / game objects however I want? I am trying to make my own gravity system if you want to know. Thanks for any help!
Answer by Kiwasi · May 20, 2014 at 02:41 AM
I use a system where I make every script check in with a static MasterClass as part of its start code. This can be complex to code, but works well when objects are dropping in and out of the collection at frequent intervals.
The MasterClass has coding that stores all GameObjects (or Components if you prefer) in a list when they report. It also checks if any of the items on the list are null and removes them.
You can also implemented other static methods and variables in my MasterClass, the usage of these will depend on the nature of the components.
MasterClass.FindClosest(Vector3 position)
MasterClass.Random()
MasterClass.DestroyAll()
MasterClass.Count
I'm not sure how this stacks up on performance against the other answers.
I would consider this one the correct answer. The best way to access every gameobject with a certain script is not to search for it every time but to add it to a list on a controller object when it is created, and remove it from that list if & when it is destroyed.
Answer by skube · May 20, 2014 at 02:23 AM
You probably want to use FindObjectByType(). It is in the documentation here.. You can easily loop through the returned array. You probably do not want to be calling it every frame though as it is not super fast.