Hi. I made a script to change the active status of two gameobjects. The script is pretty simple, if i press fire1 the gameobject 1 = active and gameobject 2 = deactive. If i press fire2 gameobject 1 = deactive and gameobject 2 = active. But I would like to make the fire1 button switch between these status. I tried to create a condition that says "if i press fire1 and gameobject 1 is active in hierarchy then set gameobjetive 1 = deactive and set gameobject 2 = active". But it didn't work out. Could someone help me? Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerPower : MonoBehaviour { public GameObject downsideWorld; public GameObject upsideWorld; void Update() { Switchworlds(); } public void Switchworlds() { if (Input.GetButtonDown("Fire1")) { downsideWorld.SetActive (false); upsideWorld.SetActive (true); } if (Input.GetButtonDown("Fire2")) { downsideWorld.SetActive (true); upsideWorld.SetActive (false); } } }
What you want is a toggle. You want to set the objects active status to what it's not - if it's true it becomes false, if it's false it becomes true. Try something like this: Code (CSharp): public class PlayerPower : MonoBehaviour { public GameObject downsideWorld; public GameObject upsideWorld; void Update() { Switchworlds(); } public void Switchworlds() { if (Input.GetButtonDown("Fire1")) { downsideWorld.SetActive(!downsideWorld.activeInHierarchy); upsideWorld.SetActive(!upsideWorld.activeInHierarchy); } } }
Hm, your approach should work... You can also keep track of your own bool variable, and when you want, flip it from true to false: Code (csharp): myBool = !myBool; Then it's just a matter of using .SetActive properly: Code (csharp): downsideWorld.SetActive( myBool); upsideworld.SetActive( ! myBool); Note the exclamation mark in the second line.
What @Serinx posts is an excellent approach too... let me add one additional thing to it: you should have a Start() function that actually sets the correct worlds active and inactive, otherwise your script will be at the mercy of how things were at the instant the scene was saved, which could lead to some weird bugs.
I'd like to thank both of you! It worked just fine with @Serinx suggestion! Its great to have someone helping you when u just started! Thanks a lot!