eastwing
eastwing

Reputation: 175

Is it fine to SetActive in Update()?

I know unity optimizes Update() method and that's why it is ok to set a variable without any condition there. But what about methods, especially gameObject.SetActive? It is really handy when you need to bind GO activity to some condition, but how does it affect performance? For instance, in UI SetActive causes canvas redraw. But I guess it's not a problem if Unity does optimize the method in Update(). So, does it?

Upvotes: 2

Views: 1819

Answers (2)

Dave
Dave

Reputation: 2842

Any code you write in the Update will be called every frame. In general I avoid using Update method if possible.

With Events and Coroutines you can run your code only when needed. It makes the code more efficient and readable.

For example instead of updating the health bar every frame in Update you can write a Coroutine that will run only on PlayerDamaged event when the player gets hit.

If your code/app is small you won't see a big difference in performance so it doesn't matter that much but it is a better practice to only use Update for the code that really needs to be called every frame.

Upvotes: 3

CoffeeStain
CoffeeStain

Reputation: 13

ya it is fine but recommend using FixedUpdate() instead of Update()

Upvotes: 0

Related Questions