Be careful while looking for GameObjects at runtime, as this can be resource consuming. Especially : don't run FindObjectOfType or Find in Update, FixedUpdate or more generally in a method called one or more time per frame.
FindObjectOfType
and Find
only when necessaryFindGameObjectWithTag
has very good performance compared to other string based methods. Unity keeps separate tabs on tagged objects and queries those instead of the entire scene.Besides the methods that come with Unity, it's relatively easy to design your own search and collection methods.
In case of FindObjectsOfType()
, you could have your scripts keep a list of themselves in a static
collection. It is far faster to iterate a ready list of objects than to search and inspect objects from the scene.
Or make a script that stores their instances in a string based Dictionary
, and you have a simple tagging system you can expand upon.
var go = GameObject.Find("NameOfTheObject");
Pros | Cons |
---|---|
Easy to use | Performance degrades along the number of gameobjects in scene |
Strings are weak references and suspect to user errors |
var go = GameObject.FindGameObjectWithTag("Player");
Pros | Cons |
---|---|
Possible to search both single objects and entire groups | Strings are weak references and suspect to user errors. |
Relatively fast and efficient | Code is not portable as tags are hard coded in scripts. |
[SerializeField]
GameObject[] gameObjects;
Pros | Cons |
---|---|
Great performance | Object collection is static |
Portable code | Can only refer to GameObjects from the same scene |
ExampleScript script = GameObject.FindObjectOfType<ExampleScript>();
GameObject go = script.gameObject;
FindObjectOfType()
returnsnull
if none is found.
Pros | Cons |
---|---|
Strongly typed | Performance degrades along the number of gameobjects needed to evaluate |
Possible to search both single objects and entire groups |
Transform tr = GetComponent<Transform>().Find("NameOfTheObject");
GameObject go = tr.gameObject;
Find
returnsnull
if none is found
Pros | Cons |
---|---|
Limited, well defined search scope | Strings are weak references |