- Home /
Why am I receiving "null" in console instead of the name?
function Update () { var troll = PlayerClass("john"); print (troll.name);
}
class PlayerClass { var name; function PlayerClass(n : String) { var name : String = n;
}
}
Answer by chillersanim · Nov 30, 2013 at 03:13 PM
You create a new variable inside the constructor which localy loks away the global variable. Instead of
var name : String = n;
you should use
name = n;
Also you should set the type of the name already on the global variable.
If I'm wrong, then I'm sorry, because I normaly work with c# and have only few experience with js.
Think the full code for you class should be something like this:
class PlayerClass
{
var name : String;
function PlayerClass(n : String)
{
name = n;
}
}
Greetings
Chillersanim
Answer by Bunny83 · Nov 30, 2013 at 03:16 PM
Well, you declared a variable "name" without a type inside the class which is initialized with null since you never assign ansthing to it.
Inside your constructor you declare another local variable name of type String and assign the parameter "n" to it. The local variable only exists only inside the constructor and will vanish once it's completed.
You should:
give your class member variable a type and
assign the value of n to the member variable instead.
Like this:
class PlayerClass
{
var name : String;
function PlayerClass(aName : String)
{
name = aName;
}
}
Your answer
Follow this Question
Related Questions
Simple Script getting Errors. 1 Answer
Error CS1519 Help 1 Answer
A node in a childnode? 1 Answer
Null Reference exception when calling using "script.gameObject.GetComponent 1 Answer
Unity Script Editor Not Working 1 Answer