I have a gameobject in my scene and other gameobjects continuously get added/destroyed as children of that gameobject. Every child that gets added has a unique name like this "Object[index]". And for example if there are 3 children, they will be named "Object, Object and Object". I was using GameObject.Find to check whether or not a certain object was already added, and if not, at that object, but people told me that that function was incredibly slow. (I use the GameObject.Find functions inside of OnInspectorGUI in a script added to the parent gameObject). What alternative should I use?
So it is an editor script? You can use Find all you want if it is an editor script since it will not be part of the final game. The best alternative to Find however is to store your references when you add new objects. No need to find something when you know about it already.
Answer by Time_Flys
5 days ago
For your particular situation I would use transform.GetChild(i) which will return the specified child of the parent gameObject. Think of the child objects as members of a list that you can grab using transform.GetChild(i)
That's indeed a function that could be very useful! I'll try it out. Thanks!
Answer by CasperK
5 days ago
GameObject.Find performance generally only matters during runtime, since you're using it indside OnInspectorGUI I'm assuming you're writing an EditorScript where it shouldn't matter.
If you still want an alternative you could use a simple manager with a dictionary since all the names are unique,
Dictionary<string, GameObject> dictonary;
and then use dictonary.ContainsKey to see if it already exists, and if not create it and use dictonary.Add.
So I should really worry about performance in editor scripts?
Thanks for the suggestion! I'm going to try it out!
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
102 People are following this question.
Check GameObject rotation in Y axis when OnTriggerEnter
How do I find other gameObject and disable it?
How to put ".transform" after "GameObject.FindGameObjectsWithTag()"
Best way to reach a component or script's function?
Using One Script for Two Separate Parent GameObjects Failing