- Home /
Switch between two light sources
I need a script to switch between two light sources, both children of the player. I have a code that can tell if it is time to switch the light sources, and to reset the variable after switching the lights. I just don't know how to activate/deactive the game objects of the lights. The light sources are a sun and a torch.
using UnityEngine;
using System.Collections;
public class LightSourceManager : MonoBehaviour {
public bool switchLights = false;
void Update () {
if (switchLights) {
lightSwap ();
switchLights = false;
}
}
private void lightSwap () {
//Put code here
}
}
What is the code to toggle if a game object is active or not?
Answer by Nirvana33 · Aug 13, 2015 at 10:54 PM
Try
if (light1.enabled==false){
light1.enabled=true;
light2.enabled=false;
}
else{
light2.enabled=true;
light1.enabled=false;
}
I get the following error, and all of my scripts are disabled and I can't do anything with scripts: Assets/Scripts/Player$$anonymous$$anagers/LightSource$$anonymous$$anager.cs(30,31): error CS1061: Type UnityEngine.Light' does not contain a definition for
Enabled' and no extension method Enabled' of type
UnityEngine.Light' could be found (are you missing a using directive or an assembly reference?)
Do you have 2 different gameobject and you want to change between them? If so, code have to work but I guess they have to be
if (light1.enabled==false){
light1.enabled=true;
light2.enabled=false;
}
else{
light2.enabled=true;
light1.enabled=false;
}
Not Enabled, enabled I'm sorry, I typed wrong
That almost works, except the only light source that creates light is the one that was enabled at the start. The other one doesn't emit light.
Answer by Pontik · Aug 14, 2015 at 03:31 AM
public Light light1, light2;
public void switchLights()
{
if(light1 && light2)
{
if (light1.gameObject.activeInHierarchy)
{
light1.gameObject.SetActive(false);
light2.gameObject.SetActive(true);
}
else
{
light2.gameObject.SetActive(false);
light1.gameObject.SetActive(true);
}
}
}
I solved this about 10 seconds before I saw your comment, but thanks :D