instance : Object is always null

I have a class:


using UnityEngine;
using System.Collections;

public class Player : Object {
   public int score;
   public Player(int _score){ score = _score }

and script in the game:


using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class Script : MonoBehaviour {

      Player player = new Player(100);
      Debug.Log("1> "+ player);
      Debug.Log("2> "+ player.score);

And as a result I get:

1> null
2> 100

And of course it makes me a lot of problems because of that null. Can someone tell me what is going on with this, and how can I get some valuable reference to this instance to make it usable in many ways?

you are thinking about this a little bit differently then the mono compiler is, and as @thraxST said the object is not null the field you are accessing is null. this analysis can be reached because Unity would have thrown a NullReferenceException pointing to your Debug.Log("1> "+ player); line.

even though you are diriving from object (which in this case is not .net Object, but instead UnityEngine object) the class has a name:string field which when you write Debug.Log(string); the mono compiler attempts to convert the object to a string, and because in managed code land we are not supposed to actually know pointer values the compiler defaults to the name field if it is found, and just return that.

the reason that you receive null is because you have given the field no default value, or initialization (kind of surprised this didn’t get a compiler error, but anyways), but are trying to access a string anyways, and so you are not getting a null pointer, but instead a null string.

to fix this either set the field to a value in the constructor (argument, or otherwise), or immediately after the constructor

Edit: above is in error. for all intents, and purposes (assuming no other home made base classes) you should be inheriting from nothing, or MonoBehavoir. MonoBehavoir gets you Unity Event system: Start() Update() OnGUI(), and physics/Input; while nothing gets you .net object (besides a few helper functions relatively clean. for simplicity sake the easiest approach if you do not want the weight of MonoBehavoir (it is not light) then inherit from nothing.

The Player object isn’t null, if it was you wouldn’t be able to player.score.

The name of the player object is null.