- Home /
Making a light turn on and off with the same button
This is what I tried so far, the first function works, the second doesn't
using UnityEngine;
using System.Collections;
public class Flashlight_Script : MonoBehaviour {
bool lightbutto=true;
public Light flashlight;
void FixedUpdate () {
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled=true)){
flashlight.enabled=false;
}
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled=false)){
flashlight.enabled=true;
}
}
}
Answer by The_Magical_Kiwi · May 21, 2014 at 07:24 PM
When you say first and second function do you mean this?
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled=true)){
flashlight.enabled=false;
}
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled=false)){
flashlight.enabled=true;
}
They aren't functions, they are if statements. This is a function.
void FixedUpdate () {
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled=true)){
flashlight.enabled=false;
}
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled=false)){
flashlight.enabled=true;
}
}
Your immediate problem is as follows:
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled=true)){
If you want to compare something to something else you need to use "==" not "=" try
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled==true)){
and
if(Input.GetKey(KeyCode.R)&&(flashlight.enabled==false)){
once you have done that you'll probably find that your light flickers on and off. This is because you have used
Input.GetKey(KeyCode.R)
What this does is return true if a key is held down. What you want is for the torch to come on/go off when ever the key is pressed down initially or when the key is released. Try
Input.GetKeyUp(KeyCode.R)
For those who do not know, the reason you need to use == ins$$anonymous$$d of = is, = sets the variable you're checking to the comparison, and == will actually compare them. === is used for an indentical comparison. $$anonymous$$G. if(true === true)
Your answer
Follow this Question
Related Questions
Why has a script I created altered every instance of an object? 2 Answers
How do I disable one button out of multiple buttons without spamming declaration? 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers