I've tried a few ways of doing it. I've asked a few friends but, nothing seems to work so far. I have changed the script several times so I don't have the other ways that I have tried anymore. However, this is the one that gave me the least errors. Others I had to continuously change it to a recommended way by Unity but ended at a dead end and nothing worked.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightActivator : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
gameObject.SetActive(false);
}
else if (Input.GetKeyDown(KeyCode.Space))
{
gameObject.SetActive(true);
}
}
}
I want to be able to turn on the ambient/directional light with just 1 button. Is that not possible?
CodePudding user response:
two little flaws here
after you do
gameObject.SetActive(false);
this very same object is now inactive -> this component as well ->
Update
is no longer being called at all ;)You always will ever only treat the first case .. the second one is never called at all since the condition will always match already with the first block!
Instead separate the logic from the target object and do e.g.
// This class should go to a different object that is always active in your scene
public class LightActivator : MonoBehaviour
{
// Here you reference the object you want to (de)activate via drag&drop in the Inspector
public GameObject theLight;
void Update()
{
// You only need one condition check
if (Input.GetKeyDown(KeyCode.Space))
{
// INVERT the active state of the light object whatever it currently is
theLight.SetActive(!theLight.activeSelf);
}
}
}
In order to keep things together you could e.g. simply make the according light object a child of the LightActivator
object ;)