- Home /
Toggle Light Component On and Off
I just watched the tutorial on toggling components on and off and while successfully toggling an object's renderer component, I can't toggle a light's light component
I used the exact same code as in the tutorial, but it just won't work...
Are you getting any exceptions? Particularly NREs, and maybe the variable isn't being assigned the light component?
Answer by aidengaydos7 · Sep 02, 2017 at 04:34 PM
Is The Script On The Light? If So This Should Work. If Not You Need To Use:
using UnityEngine;
using System.Collections;
public class EnableComponents : MonoBehaviour
{
private Gameobject lightObject;
private Light myLightComponent;
void Start ()
{
lightObject = Gameobject.Find("<Insert Objects Name>")
myLight = lightObject.GetComponent<Light>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}
Thanks for the reply, I just found out I made a newbie mistake, I wrote "void start" and "void update" with lower cases ins$$anonymous$$d of upper cases :P
How would I need to change the code so it is not working on a particular gameobject, but rather gameobjects with a specidic Tag?
Just initialize lightObject as a GameObject[] array, in Start() set it using a find by tag, then in update use a loop to loop through the array.
Thanks! I tried implementing it, but since I'm quite new to program$$anonymous$$g, I so far haven't worked with arrays. It seems there is something missing/wrong in my script in the start section:
void Start() { Collectable = GameObject.FindGameObjectsWithTag("Collectable"); myLightComponent = GameObject.FindGameWithTag("Collectable").GetComponent(); }
I got TestCubes with each a light component. cube1 can be lighted on and off with a push of a button. if i do the same on cube2, it turns on and off the light of cube1, not the light on itself. xD ? What is it I didn't get? ^^