Search Unity

Does SetActive check the current game object state ?

Discussion in 'Editor & General Support' started by liortal, Sep 25, 2016.

  1. liortal

    liortal

    Joined:
    Oct 17, 2012
    Posts:
    3,562
    I've come across a few scenarios where multiple calls to SetActive on a game object is very slow (especially with Unity's UI system, where changing an object's active state has implications on the UI and the canvas).

    Does Unity perform any check before setting the object's state? (e.g: if setting an object to active, does it verify that it is already active ?)

    I have used the following extension method which seems to give better performance in most cases, this can be done internally though:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public static class GameObjectExtensions
    4. {
    5.     /// <summary>
    6.     /// Activates or Deactivates the game object, only if the state is different than the given state.
    7.     /// </summary>
    8.     public static void SetActiveEx(this GameObject go, bool value)
    9.     {
    10.         if (go.activeSelf != value)
    11.         {
    12.             go.SetActive(value);
    13.         }
    14.     }
    15. }
     
    owlrazum, StellarVeil and JohnTube like this.
  2. Kronnect

    Kronnect

    Joined:
    Nov 16, 2014
    Posts:
    2,905
    I usually perform a safe check before assigning any property that could produce any unnecessary refresh. SetActive is one of them, also I check the current text mesh color before updating its property. And with so many properties.
     
    liortal likes this.
  3. liortal

    liortal

    Joined:
    Oct 17, 2012
    Posts:
    3,562
    Thanks for replying. is your code similar to the one i posted? or do you have anything more efficient? also, what other properties are you using this "trick" for ?
     
  4. Kronnect

    Kronnect

    Joined:
    Nov 16, 2014
    Posts:
    2,905
    It depends. I usually disable the mesh renderer instead of the whole gameobject.