In thinking about performance on iOS/Android, I was wondering what would be the best way to move 9 individual game objects (in C# by the way). Would it be better to write one script that calls multiple GameObject.Find() ? That is what my intuition tells me.
Any other advice related to performance/good practice is also appreciated.
GameObject.Find() is one of the SLOWEST functions you can call. You should avoid it in almost every case. It is much better practice to have multiple scripts, each controlling their own instance. this allows you to just write one script and have it move all 9 objects. Without more info, if you want one script to move all objects for some reason, it is better to keep references to all of them. Best practice is to just have an array as a public field and assign the objects in the inspector.
Thanks for the response skalev, my worry is that each object moves as a function of Input.GetTouch().deltaPosition but with a different constant, like obj1 moves deltaPosition.y + 10, obj2 moves deltaPosition + 20, etc… meaning I would need 9 different scripts (correct me if I’m wrong). Would this still be better?
Make the script have a public (or serialized) field that holds the constant. You can then have the same function use that field, which you will define in the inspector. So :
public class MovementClass
{
public float ConstantMotion;
void MyMoveFunction(float deltaPos)
{
transform.position += deltaPos + ConstantMotion;
}
}
My fridge probably has enough computing power to track nine objects. Performance isn’t a problem.
But if it was… GameObject.Find is comparatively slow and should never be used in performance sensitive code. Individual components are better, but will still struggle to handle several thousand objects. Your best option is normally to itterate through an array of things. This will get you to the thousands level. To get higher you need to start caching results and faking some of your objects.
Consider this pseudo, not tested code. But in principle this is also a way if you want 1 script to move several objects. You can assign objects in the array in inspector. Or you can fill the list in Start(), in there a few GameObject.Find() won’t do much harm since it’s just done once when game starts.
public class MovementClass
{
public float ConstantMotion;
public Transform[] Movers;
void MyMoveFunction(float deltaPos)
{
foreach (Transform t in Movers) {
t.Translate(deltaPos + ConstantMotion);
}
}
}
That’s new to me, but good to know. I looked up some links but they all seem to refer to List<> types, not simplest form of array. And even still they say it differs on case-by-case, some producing no garbage. But i didn’t remember the right syntax to for loop, is it
for (int i=0; i < Movers.count; i++) , or Movers.length or something? I rely on code completion feature for these, but whatever loop works.