I’m having difficulty making a spotlight torch in unity. I’m trying to make the torch switch on and off when I press the middle mouse button, but I can’t do it. I’m using a bool to determine if it should turn on or off with a bunch of if() statements. Here are two rearrangements of my script that both don’t work. If anyone could help me work out the problem I’d be very grateful.
1:
using UnityEngine;
using System.Collections;
public class ScrewdriverLight : MonoBehaviour {
//Variable to describe whether or not torch is on.
public bool Torch = false;
void Start () {
light.intensity = 0;
}
// Update is called once per frame
void Update () {
//Torch switches on and off with middle mouse button
if (Input.GetMouseButtonDown (2)) {
//If torch is off, switches on and turns Torch bool to true
if(Torch == false) {
light.intensity = 1;
Torch = true;
Debug.Log ("Torch on");
}
//If torch is on, switches off and turns Torch bool to false
if(Torch == true) {
light.intensity = 0;
Torch = false;
Debug.Log ("Torch off");
}
}
}
}
2:
using UnityEngine;
using System.Collections;
public class ScrewdriverLight : MonoBehaviour {
//Variable to describe whether or not torch is on.
public bool Torch = false;
// Update is called once per frame
void Update () {
//Torch switches on and off with middle mouse button
if(Torch == false)
{
if (Input.GetMouseButtonDown(2))
{
Torch = true;
Debug.Log ("Torch on");
}
}
if(Torch == true)
{
if (Input.GetMouseButtonDown(2))
{
Torch = false;
Debug.Log ("Torch off");
}
}
if (Torch == false) {
light.intensity = 0;
}
if (Torch == true) {
light.intensity = 1;
}
}
}
In the future I am planning to place everything under the update function under another if statement determined by a bool to check if the torch is out or if it is away.
I am fairly new to script programming instead of a node based environment, so try not to judge me too harshly.