Hello everyone
I thought I would share this little script I came up with over the past few games. It applies in the situation where for example in the same scene you have a button that would activate something else, like an options button to enable an options canvas full of stuff. T
here may be other objects to be activated/deactivated in the scene, so with this script I just assign as many as I need, then hit the button. The state of each object is toggled, which in my little example would hide the options button and show the canvas, then vice versa when someone hits a canvas close button with the same script attached.
Hopefully this is helpful to someone.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class toggleGameobjectScript : MonoBehaviour {
// button, toggle, and array of target game objects
Button theButton;
Toggle theToggle;
public GameObject[ ] targetObjects;
// In start grab whatever references we can find
void Start () {
theButton = GetComponent ();
if (theButton)
theButton.onClick.AddListener (handleClick);
else {
theToggle = GetComponent ();
if (theToggle) {
theToggle.onValueChanged.AddListener (delegate { handleClick (); });
} // if (theToggle)
} // if (theButton) else
} // start
// if we get clicked, go through the array and toggle active status
void handleClick() {
for (int i = 0; i < targetObjects.Length; i++)
targetObjects .SetActive (!targetObjects .activeSelf);
}
}
Thanks!
Matt Brown
LifeStamp Games
https://www.LifeStampGames.com