Search Unity

UI elements, SetActive vs enabled, best way ?

Discussion in 'Scripting' started by unity_5fpsmegasupergiperprogramer, Sep 27, 2019.

  1. unity_5fpsmegasupergiperprogramer

    unity_5fpsmegasupergiperprogramer

    Joined:
    Dec 1, 2017
    Posts:
    101
    Hey, everybody. What is the best way to do it, in terms of optimization?

    Turn off / on elements (buttons for example) through "gameObject.SetActive", go "enabled = " ?

    In the first case, the entire object is turned off and when the canvas is updated, the object will not be updated.

    In the second case, only the script is disabled, but when you update the canvas, the Transform object will also be updated.
     
  2. Reedex

    Reedex

    Joined:
    Sep 20, 2016
    Posts:
    389
    well for myself if i have decently complex in game menu- for example right click an item, right click details and there are more buttons inside, deactiving the whole gameobject has proved as expensive in that fram which creates lag spike.
    so what i do now is just set it that raycast doesn't hit it and put the alpha of the canvas to zero.
    no spikes or anything. not sure if its a clean way or not. that way also is the gameobject still active
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    I can't remember where I read it, but I remember seeing the suggestion to turn off the renderer vs turning off the GameObject.

    That being said, it may depend on your layout if this is your best option. You can use canvas groups to group elements together and be able to mess with alphas on grouped elements and using multiple canvases is a good idea also if you can divide things up logically.
     
    Last edited: Sep 27, 2019
  4. shawndingo

    shawndingo

    Joined:
    Oct 4, 2018
    Posts:
    83
    The only difference is-

    SetActive will either hide or show depending on true or false statement.

    Enable and disable will only activate them or deactivate them but they will still show in the scene.

    I personally use SetActive for many reasons. Like if you have a sound on and sound off button. I usually overlay these and when sound off is pressed the button will be non active and then the sound on will appear. Etc..

    So it all depends on what you need to accomplish.