can't GetCompoent in constructor?

Hi there,

do you know why this works:

var wheels:Wheel[];
var inputController:GameInput;

function Start()
{
	inputController  = FindObjectOfType(GameInput);
}

class Wheel
{
	var wheelObject:GameObject;
}

function Update()
{
	wheels[0].wheelObject.GetComponent(WheelCollider).motorTorque=inputController.acceleration;
}

while this doesn’t?:

var wheels:Wheel[];
var inputController:GameInput;

function Start()
{
	inputController  = FindObjectOfType(GameInput);
}

class Wheel
{
	var wheelObject:GameObject;
	var wheelCollider:WheelCollider;
	//initialize the wheel
	function Wheel()
	{
		//find the wheel collider
		wheelCollider=wheelObject.GetComponent(WheelCollider); //"NullReferenceException: Object reference not set to an instance of an object" at this line
	}
}

function Update()
{
	wheels[0].wheelCollider.motorTorque=inputController.acceleration;
}

the problem is that you are using the constructor on a serialized class. At all. The reason all the docs tell you never to do that, is because it doesn’t get called when you think it gets called. Because of Unity’s serialization methods, objects get created in the inspector when you add the component. The component is fully functional in the editor- it’s not just some representation.

If you try to call ‘GetComponent’ (or any other method that requires a consistent state for the rest of the engine) it can fail, because it’s quite possible that the other components don’t even exist yet, hence your NRE problems.

The simplest solution to this problem would be to implement some kind of initialization method, that invokes that code from the Start function. That would work around the problems you are having.

Ok, I found a solution, but it’s lame and I wonder if there’s a better way to do this (what if I want to have a real class constructor that is called when I would instantiate the wheel without the car?)

var wheels:Wheel[];
var inputController:GameInput;

function Start()
{
	inputController  = FindObjectOfType(GameInput);
	//initialize the wheels
	for(wheel in wheels)
	{
		wheel.Init();
	}
}

class Wheel
{
	var wheelObject:GameObject;
	var wheelCollider:WheelCollider;
	//initialize the wheel
	function Init()
	{
		//find the wheel collider
		wheelCollider=wheelObject.GetComponent(WheelCollider);
	}
}

function Update()
{
	wheels[0].wheelCollider.motorTorque=inputController.acceleration;
}