I’m sure it’s something small I’m missing, but I’m trying to declare a variable that contains a random number using Random.Range(); - however, when doing so inside of the Start() function, it simply returns Unknown Identifier.
#pragma strict
function Start ()
{
/* The problem is right here. */
var randItemsLeft : int = Random.Range(1, 8);
/* Declaring this, or any other, variable */
/* inside of the Start() function returns */
/* Unknown Indentifier: 'var name' */
}
function OnAttack ()
{
if (randItemsLeft >= 1)
{
var lootList = ['item_001', 'item_002', 'item_003', 'item_004', 'item_005'];
var randLoot = lootList[Random.Range(0, lootList.Length)];
Debug.Log("Player found " + randLoot + ".");
randItemsLeft -= 1;
}
else
{
Debug.Log("You are unable to obtain anything else from this " + name + ".");
}
}
try declaring it outside of Start().
When you declare inside a method, it belongs only to that method. If you declare inside the class (but not inside a method), then it will be visible to all methods of the class.
Example:
#pragma strict
var randItemsLeft : int;
function Start () {
randItemsLeft = Random.Range(1, 8);
}
function OnAttack () {
if (randItemsLeft >= 1) {
var lootList = ['item_001', 'item_002', 'item_003', 'item_004', 'item_005'];
var randLoot = lootList[Random.Range(0, lootList.Length)];
Debug.Log("Player found " + randLoot + ".");
randItemsLeft -= 1;
} else {
Debug.Log("You are unable to obtain anything else from this " + name + ".");
}
}
I was unaware that a variable declared inside of a method is specific to that method, thanks for that.
Just tried it the way you’ve given, and it worked just fine. I’m not sure why I didn’t think of doing it that way before. It’s sleepy time for me.
Unity doesn’t use Javascript, although some of what that page talks about regarding scope does actually apply to Unityscript (which has somewhat different rules about scope compared to C#).
Not exactly. Unity’s JavaScript is actually more akin to ActionScript. First and foremost, Unity’s JavaScript is strongly typed (like AS3). (Yes I know you can make it loosely typed but you shouldn’t and on some platforms you can’t)