Reference UI button in Script
Hi I have a scene with about 20 gameobjects with light componments. Each game object has the same script attached which enables/disables the light component using either a keyboard key or joystick button referenced through the input system. This all works fine.
I now want to change the code so the function will also be executed on each game object when I change the state of a toggle UI button. Is there a way of referencing the state of the UI button WITHOUT having to add a separate event within the button for each light game object ?
I want to avoid having to manage the events in the button if possible.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class LightOnOff : MonoBehaviour
{ private Light myLight;
// Use this for initialization
void Start()
{
myLight = GetComponent<Light>();
}
//public void LightOnOffUIButton()
//{
// myLight.enabled = !myLight.enabled;
//}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("JSB8"))
{
myLight.enabled = !myLight.enabled;
}
}
}
Answer by EricArmitage · May 02, 2020 at 09:35 AM
Ok I don't think you can reference the UI button in the code but you can reference multiple lights to a single UI button by using Game Object tags and using this code in a new game object. It finds the tagged objects and creates an array of them. It then enables / disables all the light components attached to the tagged objects.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class UILightSwitch : MonoBehaviour
{
public void TurnlightsOnOff()
{
GameObject[] myLights = GameObject.FindGameObjectsWithTag("ShortLight");
for (int i = 0; i < myLights.Length; ++i)
{
Debug.Log(i.ToString() + ": " + myLights[i].name);
myLights[i].GetComponents<Light>()[0].enabled = !myLights[i].GetComponents<Light>()[0].enabled;
}
}