Reputation: 1370
I have two functionality that need to achieve:
both must be in Update()
, i can combine it but i prefer both of them in separate script in each Movement.cs and Rotation.cs
.
So i have two method:
Update()
.Update()
.My question : does it cost performance if separate them into each individual
Update()
instead of combine in one script with oneUpdate()
.
Both script will be attach on one object, so if i have hundreds of object.
Method 1
- 100 objects and 100 script with Update()
.
Method 2
- 100 objects and 200 script with Update()
.
Another question : is it really bad to do
Method 2
?.
Upvotes: 2
Views: 6638
Reputation: 1
Here are some tests I did on how Update()
compares to some common Unity3d functions.
In the scene there are 10000 empty GameObjects with UpdateTest script on them.
The Average FPS value is smoothed heavily and I use the Mono backend.
So it seems the cost of Update()
function is somewhat less than moving an empty GameObject
with transform.localposition
.
I've used Unity3d 2020.1.5
Upvotes: 0
Reputation: 14201
This is a case of micro-optimisation. You should use any of the methods that makes more sense in your particular case and after you're done you should to some profiling.
Based on the results of profiling you'll end up knowing where and what to optimise.
Getting back to the problem at hand having 2 Updates will cost you one more function call per frame and some time when your MonoBehaviour is first loaded, but that is negligible, you'll eat a lot more CPU cycles in other parts of your code.
Upvotes: 4
Reputation: 8193
Perhaps a third option would be better for you, it elaborates on the first option but still splits your logic into two separate areas, thus achieving the loose coupling you were going for originally.
public static class Manipulators
{
public static void Rotate(MonoBehaviour behaviour, float amount)
{
Transform t = behaviour.GetComponent<Transform>();
// Do stuff with t
}
public static void Move(MonoBehaviour behaviour, float amount)
{
Transform t = behaviour.GetComponent<Transform>();
// Do stuff with t
}
}
Then in your monobehaviour...
public void Update()
{
Manipulators.Rotate(this, 15f);
Manipulators.Move(this, 15f);
}
Upvotes: 2
Reputation: 7356
If you can combine, do it. The Unity MonoBehaviours are usefull but eat quickly your resources, especially if you have many scripts running at the same time.
Check this blog ticket : https://blogs.unity3d.com/2015/12/23/1k-update-calls/
WHAT SHOULD YOU DO?
Of course it all depends on your project, but in the field it’s not rare to see a game using a large number of GameObjects in the scene each executing some logic every frame. Usually it’s a little bit of code which doesn’t seem to affect anything, but when the number grows very large the overhead of calling thousands of Update methods starts to be noticeable.
Upvotes: 3