Object is null after calling new

Hi,

I’m pretty new to Unity and also C# but i have a strange problem in one of my C# scripts that i can’t figure out.

In the script i create an object “data” from the Type TestData but even after the “data = new TestData()” data is still null according to the debugger and also if i check for null inside the code. Also strange is that i can read and write the member variables of the data Object so it’s appears not to be really null.

Possibly I’m just overlooking a simple thing here. Hope someone can help me.

using UnityEngine;
using System.Collections;

public class TestData : Object {
		public string UnityName = "";
		public string ReadableName = "";
		public string LevelGroup = "";
		public int Difficulty = -1;
		public int BestTime = -1;
		
		public TestData() {
		}
	}

public class Test : MonoBehaviour {
	private TestData m_data;
	
	// Use this for initialization
	void Start () {
		TestData data = new TestData();
		data.UnityName = "Test";
		
		m_data = data;
		
		if (m_data != null) {
			m_data.ReadableName = "OK";	
		} else {
			m_data.ReadableName = "Not OK";	
		}
		
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

object and gameobject cant be constructed by new but you have to use instantiate for it. is there a reason why you inherit testdata from object?

1 Like

Thanks that was my problem. I don’t know why I inherited but its good to know that i can’t inherit directly from object. Thank you.

Note that you are inheriting from UnityEngine.Object, not System.Object. UnityEngine.Object is Unity’s specific base class and contains native code elements hooked into the engine, and doesn’t behave well with Constructors. System.Object is always implicitly inherited from if nothing else is specified and is a sort of base class for all type in .NET.

Note: UnityEngine.Object also overrides ==, != and (bool), so that it can look as if it’s null when it’s not, (used for MonoBehaviour/GameObject to return null after Destroy(), even though they are not really null).

you can. you just must be aware of the implications from doing so. which the new/instantiate issue is one of them.
usually you inherit from monobehavior for scripts beeing attached on a gameobject to have access to functions like update, ongui onmousedown etc… and you dont inherit from monobehavior for your dataclasses for example and for objects beeing passively managed by a gameobject and have no real interaction with the game world / are not used as game objects. i put a script or class postfix in the file/classname to clearly reflect this.

GameObject can be constructed.