- Home /
Variable Vs Array?
There are two method below, which one is faster/better performance? Or have they no difference in performance?
Button[] MyButtons = new Button[49];
for (int i = 0; i <= 49; i++)
{
int Capturediterator = i;
string str = "Button" + Capturediterator;
MyButtons [Capturediterator] = GameObject.Find(str).GetComponent<Button>();
}
Button MyButton1,MyButton2,MyButton3..., MyButton50;
MyButton1 = GameObject.Find("MyButton1").GetComponent<Button>();
MyButton2 = GameObject.Find("MyButton2").GetComponent<Button>();
MyButton3 = GameObject.Find("MyButton3").GetComponent<Button>();
and so on...
MyButton50 = GameObject.Find("MyButton50").GetComponent<Button>();
For stuff like this it's better to run tests on your machine, we should try and keep this to unity specific questions (or change the title because you're not working with arrays, you're working with GameObject.find()):
using System.Diagnostics;
// ...
Stopwatch sw = new Stopwatch();
sw.Start();
// your array tests
sw.Stop();
Debug.Log("Elapsed={0}",sw.Elapsed);
Answer by sleepandpancakes · Jun 09, 2017 at 06:09 PM
Iterating through an array has a negligible impact on performance, at least for these purposes. The first version is clearly better than the second, not for performance reasons, but because the code is MUCH more concise. There's absolutely no reason to hard code each assignment. Remember that you want to repeat yourself as little as possible in your code.
However, neither option is good because GameObject.Find() is frankly a terrible and non-performant way to assign references. That function will search your entire scene for an object with a matching name, and if you're doing that 50 times in a row it will have a significant impact on performance. I would assign the references in the inspector (which lets you sidestep assigning the references in the code altogether). If you need to do it by code then make sure all the buttons are components of one GameObject (or it's children) and use GameObject.GetComponents() or GameObject.GetComponentsInChildren()
Answer by Glurth · Jun 09, 2017 at 06:09 PM
The second is insignificantly faster, but significantly harder to write. More important is how often you will do it: "Find" is slow, so you should try to do this only once, like on start, and SAVE the found buttons for use in say .. Update.
Your answer
Follow this Question
Related Questions
images assigned to gameobjects by tag 2 Answers
How can I fill an image array with a script 1 Answer
How to load different sprites on a panel based on player level 1 Answer
Getting an error trying to assign a value to an array of classes element 0 Answers
New Gui 4.6 - How to use new GUI for inventory system 1 Answer