I believe I understand function Start() and function Awake() but I wrote a piece of code that isn’t working the way I thought it would. I can get around it but I’d rather understand why it doesn’t work. The script is below.
When written as is below I get the error “Unknown identifier ‘lives’” The error is referring to the line HUDLives = lives.ToString();
function Start()
{
var lives :int = 3; //set lives to 3
var HUDLives :String;
}
function Update ()
{
HUDLives = lives.ToString(); //Set the HUD string to the # of lives left
guiText.text = HUDLives; //set the guiText to the # of lives.
}
When I initiate var lives before function Start() like the code below, it works fine.
var lives :int;
function Start() //first function called -> even called before function Start()
{
lives = 3; //set lives to 3
var HUDLives :String;
}
function Update ()
{
HUDLives = lives.ToString(); //Set the HUD string to the # of lives left
guiText.text = HUDLives; //set the guiText to the # of lives.
}
I’m just not sure why I can’t initialize and set the value of the variable in function Start() and then refer to it in function Update(). If function Start() is called first, shouldn’t function Update() known of the variables existence?
Thank you for your help, it is very much appreciated.
Any variable you declare within a function does not exist outside the function. thats why update does not know about its existance, you never declared it for the whole class you only declared a variable local to the start function
If you want it to exist outside ie for the whole class you must declare it outside.
thats why version 2 works or would work if the code there wasn’t incorrect (get rid of the start line there after function start)
When you declare a variable in a space surrounded by curly braces { } then the variable is local to it. You can’t access this variable outside this space !
If a variable is declared in a class that is outside all functions then that variable is Global to all functions .
For example :
Class MonoBehaviour
{
int a , b ;
void start()
{
int a ; // this ‘a’ is local variable to start() function .
// The ‘a’ declared outside will not be conflicting with this ‘a’.
// you can’t access outsider ‘a’ in this function.
// But you can access b here (as it is global to all function in this class .)
a =10;
b=10;
}
void Update()
{
print(a); // this won’t print 10 !
print(b); // this will print 10.
}
}
Doh! So simple and I understood that concept all along but I got to caught up in the Start() and Awake() functions.
I was thinking that I should define the lives var inside there so var lives wouldn’t get called again and reset lives back to 3. I guess it’s one of the bad habits I obtained from GMaker.
you are right, didn’t realize that it could be part of the comment. I never comment like that cause its not really readable in general and not auto documentable like the ///
you get from MD / VS when putting it at the top of a function where you can fold the whole block.