When there are about 400 instances
It takes 0.3ms to run this line of code, which is too expensive
Is there any way to optimize performance
I am learning about Matrix, does it help
If you think the .3ms cost for this is too high, you might bee able to improve it by adding all of these objects to a list and moving all of them within a single LateUpdate call on a common controller object. Then remove all of their LateUpdate calls:
This may give you a small performance boost because most of the cost of your original code is likely from the overhead of the individual method calls themselves.
You can pre-measure this by running the game with the internals of the function commented out. Whatever remaining time is spent in the LateUpdate() is going to be pure function overhead. That’s the only amount of time you can save.
All optimization is premature if you don’t actually measure a performance problem.
Yeah 400 MonoBehaviours all running LateUpdate was my guess as well. I’d do as already suggested above, moving all these to a single LateUpdate call, and use the profiler to compare against the 400 MonoBehaviour performance.
public List<Transform> transforms = new List<Transform>();
public List<Transform> targetTransforms = new List<Transform>();
public List<Vector3> offsets = new List<Vector3>();
private void LateUpdate()
{
for (int i = 0; i < transforms.Count; i++)
{
transforms[i].position = targetTransforms[i].position + offsets[i];
}
}
0.25ms → 0.18ms, saving 0.07ms, I guess addressing wastes too much time, 10ms/0.18ms=55, which means that when there are 400 monobehaviours, each monobehavior can only have 55 lines of code. It’s too hard:(
That’s not exactly how this works. However if you are working on a game where you have a few hundred or a few thousand objects, then that in itself demands optimization. For 400 i would not stress it too much, unless you have 400 objects doing complex things. When you have thousands of objects, then you will have to look into different ways of implementing them. DOTS is made for this kind of thing. That said, if you are still a beginner i do not recommend going that route. Optimizations in general are an advanced topic. What a lot of people do not understand is that games with lots of entities (like Factorio) will require a lot more optimizations than, say, your generic shooter game will. Even with tools like DOTS that are made to make this easier, it’s still a lot to learn, especially considering programming in DOTS is way different than what you are used to by now. It’s not even object oriented anymore, since object oriented programming kinda sucks for these high-performance many-units scenarios.