Hello,
I’m still learning this myself but I’ve put together something which after 30 seconds, calculates a random number in the array and outputs this to “Result”. I want to check if result is equal to a particular output and do something. Everything works apart from checking what result holds.
#pragma strict
var timer : float = 30.0;
var countDown : boolean = true;
var choices : int[] = [1, 2];
var result : int;
var hasChosen : boolean = false;
function Update()
{
if(countDown)
{
timer -= Time.deltaTime;
}
if(timer <= 0 && !hasChosen)
{
ChooseNumber();
countDown = false;
}
if(result == 1) //THIS DOESN'T WORK!
{
//DO SOMETHING
}
else
{
//DO SOMETHING ELSE
}
}
function ChooseNumber()
{
var howManyThings : int = choices.length;
var myRandomIndex : int;
myRandomIndex = Random.Range(0, howManyThings);
result = choices[myRandomIndex];
hasChosen = true;
}
Why do you say it “doesn’t work”? Comparing an int variable against a literal int value always “works”, what you mean, I guess, is that it evaluates to false. It is perfectly possible for your code to pick the value “2” from the choices array in a lot of consecutive runs.
Or does your code crashes in some way?
You can quickly debug your code by printing the “result” variable to the console after it’s selected and before it is compared. You can debug your code with a real debugger, open MonoDevelop, double click at the left of the line “if(result == 1)” to set a breakpoint (you should see a red circle when the breakpoint is there). Press the Play button in MonoDevelop and attach it to the Unity process. It should be detected automatically, so just press the “Attach” button. Now run your game from Unity and MonoDevelop should stop at that line. Move your mouse over the “result” variable in that line and you’ll see it’s value.
If you want to make sure that your ChooseNumber code is working correctly you can set breakpoints there too.
The error console in Unity had the debug warnings disabled, I re-enabled and it shows the debug log outputs. It was working after all.
I don’t know why they were turned off, easy fix. Thanks to everyone who tried to help!