Unknown Identifier : Hunger?
Hello! I am very sorry that I am probably asking a very basic question. I am not that good at scripting in Unity. I am trying to create a script that will display when hunger = 0, the game restarts. This is my script that I want to fix:
#pragma strict
function Start () {
var Hunger = 100;
}
function Update () {
}
function OnGUI()
{
GUI.Label(Rect(0,0,100,100),"Hunger: "+Hunger);
}
function onHungerDeath()
{
if (Hunger <= 0) {
Application.LoadLevel(0);
}
}
Here is the error that is displayed:
Assets/Scripts/variabledisplay.js(12,42): BCE0005: Unknown identifier: 'Hunger'.
Assets/Scripts/variabledisplay.js(16,7): BCE0005: Unknown identifier: 'Hunger'.
Thank you for taking your team to help me.
Answer by Landern · Dec 20, 2016 at 06:20 PM
You need to declare Hunger outside of the scope of a function, in the function it is not available and this doesn't work like javascript and it's closure.
Update your script like so:
#pragma strict
var Hunger: int;
function Start () {
Hunger = 100;
}
function Update () {
}
function OnGUI() {
GUI.Label(Rect(0,0,100,100),"Hunger: "+Hunger);
}
function onHungerDeath() {
if (Hunger <= 0) {
Application.LoadLevel(0);
}
}
@Landern, thanks for your response, however 3 more errors pop up when I copied this in to my unity:
Assets/Scripts/variabledisplay.js(12,7): BCE0005: $$anonymous$$ identifier: 'Hunger'.
Assets/Scripts/Shop.cs(3,0): error CS1525: Unexpected symbol `var'
Assets/Scripts/variabledisplay.js(12,7): BCE0005: $$anonymous$$ identifier: 'Hunger'.
This doesn't make sense if the variable is accessible to the entire class/.js file, make sure the variable is specified as above.
In the case of
Assets/Scripts/Shop.cs(3,0): error CS1525: Unexpected symbol `var'
If you put the same code into a c# class(.cs extension) then it can not infer the type with no value, in the case of the .cs just use something like:
public int Hunger;
or
public int Hunger = 100; // you can initialize the value during declaration.
The above c# declaration can be applied to the .js class as well.
var Hunger : int = 100; // you can then remove the initial set of Hunger from the Start function.
@Landern, thanks for your response. It turns out that I was using C# to program this ins$$anonymous$$d of Javascript. (I feel so embarrassed, lol.) If it wasn't for you responding and taking your time, I would've given up on this project! Thanks.
$$anonymous$$eep your scripts in the same lingo m8.
JS FOR LIFE!