pragma strict
function Start () {
}
function Update () {
if(Input.GetKeyDown(KeyCode.Space))
light.intensity = 5;
light.range = 20;
}
//if you could please explain what you did and why. I have just started learning Unity script.
pragma strict
function Start () {
}
function Update () {
if(Input.GetKeyDown(KeyCode.Space))
light.intensity = 5;
light.range = 20;
}
//if you could please explain what you did and why. I have just started learning Unity script.
This is a breakdown of how your script is running.
Update is called every ‘frame’.
Check if space has just been pressed (not being held).
intensity = 5 …
intensity = 20 …
so Immediately, you have changed the value twice.
You want something that can remember 2 types of ‘state’ (a condition that can remember on/off)
There is something called a boolean that is a variable type, it can hold a value called true or false.
So now there is something that you can use, and check it’s state, like a light switch (but yours is a touch-lamp) =]
Up is ON (true) , down is OFF (false)
Here’s how to write a boolean : var myLightSwitch : boolean = false;
Then, to change it in the script : myLightSwitch = false;
So now before changing the switch you have to check “am i on or off (true or false)?”
this can be confusing at first, but is very easy.
normally an if would look like : if (myLightSwitch == true) { do stuff;}
but for true what you will see written is : if (myLightSwitch) { do stuff;}
. this is the same as saying myLightSwitch == true
for false what you will see written is : if (!myLightSwitch) { do stuff;}
. Note the ! mark this is like saying if( Not myLightSwitch is true )
SO put it all together (make a new script, copy-paste the following code, check the comments in the script) :
#pragma strict
// Declare Variables
public var myLightSwitch : boolean = false; // public, so you can see it in the Inspector
private var theIntensity : int; // private, so you can Not see it in the Inspector
function Start()
{
// Assign values to Variables
theIntensity = 0;
if (myLightSwitch == true) // check if myLightSwitch was changed to true in the Inspector at start
{
theIntensity = 1; // light is on
}
light.intensity = theIntensity;
}
function Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// check if light is On or Off
if (myLightSwitch) // if (TRUE), light is ON. ** Remember that (!myLightSwitch) means if (FALSE)
{
theIntensity = 0; // light off
light.intensity = theIntensity;
myLightSwitch = false; // change boolean to now false (off)
}
else // did not fill the condition set in the above if statement (no it wasn't true)
{
theIntensity = 1; // light on
light.intensity = theIntensity;
myLightSwitch = true; // flip the switch !
}
}
}
hope this helps =]