- Home /
Spotlight on/off
Hi, I want my character to have a flashlight, that they can turn on/off by hitting a key, and I dont know how to do it. I saw the same question, where they said to use this script:
var flashlight : GameObject;
var myLight : Light = flashlight.GetComponent("Light"); function Update() {
if (Input.GetKey("f")) { myLight.enabled = !myLight.enabled; }
}
The problem is that its in C#, and I dont know how to write the same code just in JavaScript. Can you help me with the script?
Answer by · Sep 24, 2010 at 08:29 AM
Looks like it's only the declaration that needs updating - note the syntax change.
(Note that the gameObject name is 'flashlight', not lightPoint - as per comments)
public var flashlight : GameObject;
function Start() { var myLight : Light = flashlight.GetComponent("Light"); }
function Update() { if (Input.GetButtonDown("Fire1")) { myLight.enabled = !myLight.enabled; } }
Let me know if there are any other problems - preferably the compiler error(s)!
I get the compiler error BCE0005: $$anonymous$$ identifier: 'lightPoint'.
That's because lightPoint is referring to a gameObject that should have been declared further up in the script. I can help you track it down, if you can't find it - just update your question with the full script.
I'm new to the Unity, so I still have problems with it. Here is what I do:
var flashlight : GameObject; var myLight : Light = Flashlight.GetComponent("Light");
if (Input.Get$$anonymous$$ey("f")) { myLight.enabled = !myLight.enabled; }
in the Character object. I set the flashlight and mylight variable to the Flashlight, but it give me this code : Object reference not set to an instance of an object
UnityScript (as with most languages) is case sensitive. If you declare it as "flashlight", you need to call it as "flashlight", rather than "Flashlight". I'll update my answer to use your script - your question calls it "lightPoint", which is why you got that error!
Okay, it works now, but console still writes an error : Object reference not set to an instance of an object. Even that I had changed ALL the variables and the name of the spotlight to flashlight (with lowercase letters). I'll add the script as an answer to my own question.
Answer by Martin 3 · Sep 24, 2010 at 09:32 AM
var flashlight : GameObject;
var myLight : Light = flashlight.GetComponent("Light"); function Update() {
if (Input.GetKey("f")) { myLight.enabled = !myLight.enabled; }
}
For future reference, this should go in the Question field, not as a new answer.
sorry fixed it but it turns on and off fast... sometimes doesnt turn on/off Y
Answer by Squeekpro107 · Apr 13, 2016 at 11:26 AM
Your answer