Null reference of component that is assigned in the inspector and used in a property

Hi,
i get a null reference exception because i set .enabled of a public collider inside a property. I did a workaround and return if the collider is null, but i wonder why the error occurs and if there isn’t any better way to solve it?

using UnityEngine;
using System.Collections;

public class BaseClass : MonoBehaviour {

	public Collider col;
	bool isColliderActive;

	BaseClass(){
		IsColliderActive = false;
	}

	bool IsColliderActive{
		get{
			return isColliderActive;
		}
		set{
			isColliderActive = value;
			col.enabled = isColliderActive; 
			// NullReferenceException: Object reference not set to an instance of an object
			// This error msg appears three times before the collider seems to be loaded
		}
	}
}

You shouldn’t ever define a constructor in a MonoBehaviour.

I think what’s happening is that the constructor is being called before the object is set up. So when the constructor calls the property setter, col hasn’t been assigned.

Try changing the constructor to an Awake() function, which is what one would normally use to do constructor-like things in a MonoBehaviour. Awake() is called after the connections defined in the inspector have been set up.

As an aside: it’s far from clear what the point of this code is. Your isColliderActive field and IsColliderActive property don’t appear to achieve anything that couldn’t be done much more easily by just using col.enabled.