Search Unity

SetActive(true) works, but (false) doesn't.

Discussion in 'Scripting' started by b4gieta, Jul 31, 2020.

  1. b4gieta

    b4gieta

    Joined:
    Jul 17, 2018
    Posts:
    97
    Hi, I'm trying to make simple switch. The problem is that it works (debug logs, which you can see in script below show properly) but only the SetActive(false) after turning on switch doesn't work. GO is GameObject which is child to the GameObject with script.
    Code (CSharp):
    1. public class Switch : MonoBehaviour
    2. {
    3.     public bool playerHere;
    4.     public GameObject GO;
    5.     public float delay;
    6.  
    7.     void OnTriggerEnter2D(Collider2D col)
    8.     {
    9.         if (col.gameObject.tag == "Player")
    10.         {
    11.             playerHere = true;
    12.         }
    13.     }
    14.     void OnTriggerExit2D(Collider2D col)
    15.     {
    16.         if (col.gameObject.tag == "Player")
    17.         {
    18.             playerHere = false;
    19.         }
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void Update()
    24.     {
    25.         delay = delay + Time.deltaTime;
    26.  
    27.         if (Input.GetButton("Interact") && playerHere && delay > 1f)
    28.         {
    29.             if (GO.activeSelf)
    30.             {
    31.                 Debug.Log("Turning off");
    32.                 GO.SetActive(false);
    33.                 delay = 0f;
    34.             }
    35.  
    36.             if (!GO.activeSelf)
    37.             {
    38.                 Debug.Log("Turning on");
    39.                 GO.SetActive(true);
    40.                 delay = 0f;
    41.             }
    42.         }
    43.     }
    44. }
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    The issue is with your logic, both are wrapped in an if statement so the first is making the case true for the second. You can change the second statement to else if and that would fix it. Although you likely want to use GetButtonDown and not GetButton so it only registers true for one frame.

    You could, however, just remove the if statements and reduce the code a little by setting it to the opposite of its current state;

    Code (CSharp):
    1. if (Input.GetButtonDown("Interact") && playerHere && delay > 1f)
    2. {
    3.     var active = GO.activeSelf;
    4.  
    5.     Debug.Log(active ? "Turing Off" : "Turning On");
    6.     GO.SetActive(!active);
    7.     delay = 0f;          
    8. }
    9.  
     
    Brathnann likes this.