Home > other >  Why can't I "unhide" my gameobject in unity by using SetActive(true)
Why can't I "unhide" my gameobject in unity by using SetActive(true)

Time:04-13

I am making a little game and I want my character to disappear until you press space, but I don't want to destroy it since it has a script inside. I tried what I wrote below, but it didn't work.

void Start () {
gameObject.SetActive(false);
}
void Update () {
if (Input.GetKeyDown(Keycode.Space)) {
gameObject.SetActive(true);
}

Have any clues to fix it or replacement code?

CodePudding user response:

You set the GameObject to disabled with SetActive(false). As a result, the Update() method is no longer executing. Because of this, the code that will unhide your character can never run.

There are many ways to get the behavior you want, but the simplest I can think of is this: Instead of disabling the entire gameobject, just disable the renderer (whether it's a sprite renderer or mesh renderer). This will make your character disappear, but this script will keep running.

Example:

public Renderer renderer; // drag your renderer component here in the Unity inspector

void Start ()
{
  renderer.enabled = false;
}

void Update () 
{
  if (Input.GetKeyDown(Keycode.Space))
    renderer.enabled = true;
}

Another approach (and I think, better) is to create a child object of your character's GameObject, call it "Body", and place everything that deals with rendering your character in there. Then disable/enable that child gameobject as desired.

CodePudding user response:

Using gameObject.SetActive(false) disables the gameObject and all its components, including the script you're running so it can't turn itself on if the script driving it is off.

If you add the script to a parent object of the object you're trying to disable you can get the effect you're looking for like this:

public gameObejct childObject;

    void Start()
    {
        childObject.SetActive(false);
    }

    void Update()
    {
        if (Input.GetKeyDown(Keycode.Space))
        {
            childObject.SetActive(true);
        }
    }
  • Related