- Home /
If statement not reading variable
Hey i have cube which is a "win" and a sphere which is the "goal" The idea is you pick up the win cube and then that opens the goal, and you can go in. The first collision detection works finde and the cube destroys properly and eerything, but the second, with "if(goalopen ==true)" does not.
The code works perfectly well if i delete the "if(goalopen ==true)" statement, but then you can go directly to the goal without picking up the cube, which is not what i want..
I would really appreciate if anyone could point out my mistake, thanks in advance! :)
#pragma strict
var guiWin : GUIText;
var score;
var target : lysskifte;
var target2 : lyskifte2;
var goalopen;
function Start () {
guiWin.text = " ";
var score = false;
var goalopen = false;
}
function Update () {
}
function OnTriggerEnter(col : Collider){
if(col.collider.name == "win"){
guiWin.text = "Cube Collected";
print("collison detected");
var score = true;
print(score);
target.score = true;
target2.score = true;
var goalopen = true;
Destroy(col.gameObject);
yield WaitForSeconds(3);
guiWin.text = "";
}
else if(col.collider.name =="goal"){
if(goalopen == true){
Destroy(col.gameObject);
guiWin.text = "You Win";
print("goal!");
yield WaitForSeconds(6);
guiWin.text = "";
}
}
}
Answer by Chronos-L · May 17, 2014 at 09:40 PM
Change this:
function OnTriggerEnter(col : Collider){
if(col.collider.name == "win"){
...
var goalopen = true;
...
}
...
}
to this:
function OnTriggerEnter(col : Collider){
if(col.collider.name == "win"){
...
goalopen = true;
...
}
...
}
and remove all var in Start()
and other functions. You are not modifying the existing variable when you put the keyword var
. Example, var score = false
in Start()
will create a local variable score
and set it to false
; that will not set the first score
in line 3 to false
.
Please tick the 'Accept this answer as correct' checkmark up there beside the thumbs icons
Your answer

Follow this Question
Related Questions
How to GetComponent once for multiple comparisions 2 Answers
Function with multiple if, else if statements. 1 Answer
toolbar and if selection 0 Answers
ANOTHER Boolean Problem 1 Answer
Questions of the Coroutines 1 Answer