Search Unity

Toggling a purchased gameobject on and off in inventory

Discussion in 'Scripting' started by okaybj, Jan 31, 2020.

  1. okaybj

    okaybj

    Joined:
    Nov 15, 2018
    Posts:
    33
    I am trying to do some in game character customization and I'm running into a big problem. I have a game object the user wants to buy/equip (lets call it helmet) in the shop, the user goes to the shop and if they have enough coins they buy the helmet and i run this code:

    Code (csharp):
    1.  
    2. if (frogHelmetSold == 1)
    3. {
    4. frogHelmet.SetActive (true);
    5. frogHelmetLocker.SetActive (true);
    6. }
    7. else
    8. {
    9. frogHelmet.SetActive (false);
    10. frogHelmetLocker.SetActive (false);
    11. }
    12.  
    This will purchase the helmet, equip it and put it in the users locker and is working fine. BUT when i try to toggle the helmet on and off with the frogHelmetLocker button, like this:

    Code (csharp):
    1.  
    2. public void toggleFrogHelmet()
    3. {
    4. frogHelmet.SetActive (!frogHelmet.activeSelf);
    5. }
    6.  
    When debugging the value for activeSelf is always false. Which at least should mean the Helmet turns off but it doesn't.
     
  2. Vanamerax

    Vanamerax

    Joined:
    Jan 12, 2012
    Posts:
    938
    Have you tried using GameObject.activeInHierarchy? If you are disabling a parent object of the frogHelmet then checking activeSelf won't work. Hard to say what is wrong without knowing the setup in the editor.
     
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    If a parent of frogHelmet is set to inactive, that will prevent frogHelmet from being activeInHierarchy, but activeSelf should still toggle. (The helmet might not actually appear in the game, but the check box in the Unity inspector for it being active should go on and off.)

    I don't think the problem is in the code you posted, but probably something else in the larger environment. Some possibilities include:
    • Despite your expectations, you are never actually running the toggleFrogHelmet() function in the first place. (You could test this by adding Debug.Log calls in there.)
    • The variable "frogHelmet" isn't set to the object that you expect, so you are actually toggling something else.
    • The frogHelmet include some component with an OnEnable() or OnDisable() function, which automatically runs when it is made active or inactive, and is somehow messing you up (e.g. it could be programmed to turn itself back on whenever it gets turned off).