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;

}	

}

2 Answers

2

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

No, you're totally right. Thank you. :)

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:

  1. give your class member variable a type and
  2. assign the value of n to the member variable instead.

Like this:

class PlayerClass
{
    var name : String;
    function PlayerClass(aName : String)
    {
        name = aName;
    }
}