I don’t want to call them every frame, just want to know which one’s best practice and faster?
Hey Amir, if you really care about performance you don’t want to use either of those, as they rely on going through lists to find objects, what you want is to actually have your own reference to objects in your code to access them.
However, since you asked, here is the results of both, doing a crude testing with 10000 iterations:
Time for FindGameObjectWithTag 00:00:00.0009976
Time for FindObjectOfType 00:00:24.9714055
DateTime now = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
GameObject obj = GameObject.FindGameObjectWithTag("Respawn");
}
DateTime after = DateTime.Now;
TimeSpan result = after - now;
Debug.Log("Time for FindGameObjectWithTag " + result);
now = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
Image obj = (Image)FindObjectOfType(typeof(Image));
}
after = DateTime.Now;
result = after - now;
Debug.Log("Time for FindObjectOfType " + result);