Best alternative for GameObject.Find
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[0], Object[1] and Object[2]". 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?
Thanks
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 aFeesh · Mar 20, 2017 at 03:23 PM
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 · Mar 20, 2017 at 03:24 PM
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!
Your answer
Follow this Question
Related Questions
How do i convert game object counts, into int, and put into string? 0 Answers
How to put ".transform" after "GameObject.FindGameObjectsWithTag()" 1 Answer
How do I find other gameObject and disable it? 2 Answers
How many triangles and verts are too much (for mobile devices)? 0 Answers
Using separate GameObjects for "generic" scripts (Performance) 1 Answer