Nikita Chernykh
Nikita Chernykh

Reputation: 270

Check if object is active.Unity

I want to check if object is active and if it is I want to inactivate other objects. Here is my method. It is not the best one but I just want it to work. This method I have doesn't work right because it only runs once even though I have it in update(). Need some help here...

update: the problem is that when I choose the selection that selection becomes true and because another selection is already true this code is not working and right now I don't know how I can fix it.

public GameObject selectionTop, selectionBot, selectionSplash, selectionFloor;

private void Update() => Check();
public void Check() 
{
    if (selectionTop.activeSelf) 
    {
        selectionBot.SetActive(false);
        selectionSplash.SetActive(false);
        selectionFloor.SetActive(false);
    }
    else if (selectionBot.activeSelf) 
    {
        selectionTop.SetActive(false);
        selectionSplash.SetActive(false);
        selectionFloor.SetActive(false);
    }
    else if (selectionSplash.activeSelf) 
    {
        selectionTop.SetActive(false);
        selectionBot.SetActive(false);
        selectionFloor.SetActive(false);
    }
    else if (selectionFloor.activeSelf) 
    {
        selectionTop.SetActive(false);
        selectionBot.SetActive(false);
        selectionSplash.SetActive(false);
    }
}

Upvotes: 1

Views: 12349

Answers (3)

Colton White
Colton White

Reputation: 976

Update only gets called when the GameObject its script is on is activeInHierarchy and the script is enabled. My guess is that you have this script on one of the GameObjects that is being disabled and that is causing update not to get called.

So I would move this script to another game object that is not used one of the "selection" game objects so that update will always be called.

Upvotes: 3

Plastic Sturgeon
Plastic Sturgeon

Reputation: 12527

Use a variable to store what the current selection is. Then when a new selection is made, hide the current selection, then call check.

  • or -

Make a function that hides all the items. Call that each time. Then set the items you want active.

Upvotes: 0

Sabrina_cs
Sabrina_cs

Reputation: 421

I'm not sure if this is a silly answer, I've never worked with the game sdk but just looking at the code...

the

    if(...)
    {
    }
    else if (...)
    {
    }

I've always seen it written this way, but maybe it's just me, you can check if your code is executed both using the debugger and if it is not, you can use the Debug.Writeline to let something be printed inside the routines on your debug screen to see which code is executed.

Upvotes: -1

Related Questions