Search code examples
unity-game-enginegameobject

What is the difference between GetComponent<Image> ().enabled and .SetActive (false); in unity


I have been trying to use SetActive () to turn on and off GameObjects.

I couldn't figure it out and ended up using:

 GameObject.Find ("ObjectName").GetComponent<Image> ().enabled = false;

to turn off an image.

I am not trying to use the same script to turn off a GameObject that has multiple animations nested inside it.

GameObject.Find ("ObjectName").GetComponent<???> ().enabled = false;
GameObject.Find ("ObjectName").SetActive (false);

I am not sure what goes in the <>, but I have read I can do it with SetActive (), but that doesn't seem to work and gives me an "Object Reference not set to object" error.

So what is the difference between these two and how would I use them properly?


Solution

  • Using GetComponent allows you to enable/disable and interact with specific components on a GameObject.

    For example, you may need to disable a GameObject's rigidbody at some point, but you still want that object, and everything else on it to be active. So you could simply say:

    GameObject.Find("MyObject").GetComponent<Rigidbody>().enabled = false;
    

    Note that what goes inside the "<>" is the class name of the component you want to interact with.

    For example, if you had a script you have written yourself on a gameobject called MyScript, you could grab hold of it like so:

    MyScript script = GamesObject.Find("MyObject").GetComponent<MyScript>().enabled = true;
    

    Additionally, another good use of GetComponent is reading information from a script on an object.

    For example, if you had a script called Health with a public variable HitPoints on an object, another script could gain access to that information using GetComponent.

    if( enemyGameObject.GetComponent<Health>().HitPoints < 0 )
    {
        enemyGameObject.SetActive(false);
    }
    

    Using SetActive will enable and disable a GameObject entirely. This is less expensive than deleting / making a new object, and is thus often used in techniques like Object Pooling.

    For example, if you had a GameObject that you needed disabled, but you knew you were going to need it again soon, it is far less expensive to just call

    MyGameObject.SetActive(false);
    
    ...
    
    MyGameObject.SetActive(true);
    

    Than it is to delete that object entirely, and then make a new one when you are ready for it again.