- Home /
How do i make a Spotlight able to turn on and off in Javascript?
I have been trying all day to get this too work but it just doesn't seem like it want to.
The script errors i get is usually Unkown Identifier: "myLight" I could guess this is as simple as that. But i'm new to both programming and unity.
Heres my code in Javascript:
public var ficklampa : GameObject;
function Start()
{
var myLight : Light = ficklampa.GetComponent("Light");
}
function Update()
{
if (Input.GetKeyDown("f"))
{
myLight.enabled = !myLight.enabled;
}
}
Answer by robertbu · Oct 23, 2013 at 04:07 PM
You are very close. Your issue is that you are declaring 'myLight' locally in Start(). So once it is out of scope, it no longer exists. As a minor point, don't use GetComponent() with a string parameter. Pass the type/class. Try this:
public var ficklampa : GameObject;
private var myLight : Light;
function Start()
{
myLight = ficklampa.GetComponent(Light);
}
function Update()
{
if (Input.GetKeyDown("f"))
{
myLight.enabled = !myLight.enabled;
}
}
Note if you put the script on the light game object, you can boil this script down to:
function Update() {
if (Input.GetKeyDown(KeyCode.F)) {
light.enabled = !light.enabled;
}
}
Unfortunately still doesn't work :S Doesn't get a script error now tho. It just doesn't work.
I just tested the above code in a simple scene and it worked fine. Try it this way to verify:
Create a new scene
Create a cube
Create a light...directional light or a point light positioned so that it is illu$$anonymous$$ating the cube.
Create an empty game object and attach the script
Drag the light to the 'Flicklampa' variable in the inspector.
Run the app.
This way you can verify the code.
Answer by Miziziziz · Oct 23, 2013 at 04:48 PM
Make a spotlight. Make an empty GameObject.
make a script like this:
var ficklampa : GameObject;
var onOff : boolean;
function Update ()
{
if(Input.GetKeyDown(KeyCode.F))
{
if(onOff == true)
{
ficklampa.SetActive(true);
onOff = false;
}
else
{
ficklampa.SetActive(false);
onOff = true;
}
}
}
untested script, but shouldn't be any serious errors. Just add this script to the empty GameObject, and drag the spotlight into the slot in the inspector for ficklampa
Your answer
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Luz parpadeante con bateria 0 Answers
Rotation and movement? 1 Answer
Add delay to javascript? 1 Answer