Hi guys. I’m very new to coding and have been trying to figure out a couple of things using brute force and reference to the scripting api (where I can understand it). I’ve been trying to make a light switch script using raycasting. I’ve come upon an entirely brand new problem wherein putting two objects with the same script on in a scene make neither of them work. The extra weird thing is that this is NOT the case in my test level (where I wrote the script). Here it is:
public class LightSwitch : MonoBehaviour
{
[SerializeField] Light myLight;
[SerializeField] Camera playerCam;
[SerializeField] float range = 5f;
[SerializeField] AudioSource audioSource;
[SerializeField] Material offMaterial;
[SerializeField] Material onMaterial;
private void Start()
{
onMaterial = myLight.transform.GetComponent<Renderer>().material;
}
void Update()
{
RaycastHit hit;
if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range))
{
if (Input.GetKeyDown(KeyCode.E))
{
LightSwitch target = hit.transform.GetComponent<LightSwitch>();
if (target == null) return;
target.ProcessLight();
target.ChangeMaterial();
audioSource.Play();
}
else
{
return;
}
}
else
{
return;
}
}
void ProcessLight()
{
myLight.enabled = !myLight.enabled;
}
void ChangeMaterial()
{
if(myLight.enabled == true)
{
myLight.transform.GetComponent<Renderer>().material = onMaterial;
}
else
{
myLight.transform.GetComponent<Renderer>().material = offMaterial;
return;
}
}
}
Deepest apologies for my generally crappy coding too. I will go back and clear it all up as soon as I get it working, haha.
If anyone can help me with how to get one light switch to toggle an array of lights that would be really cool too.