Object Reference and Instancing Problem

Hello! Got a script I wanna fire upon collision right heree…

	void OnTriggerEnter(Collider col)
	{	
		var target = col.gameObject;
		var com = target.GetComponent<PlayerStateSync>();

		bool isSneaking = com.crouching;

		Debug.Log(isSneaking);
    }

Got no errors when I compile, no errors at runtime UNTIL the collision happens and throws

NullReferenceException: Object reference not set to an instance of an object
MyScript.OnTriggerEnter (UnityEngine.Collider col) (at Assets/Game Scripts/MyScript.cs:22)

So the error is happening where I’m declaring the bool. Not really sure what’s going on… I’m guessing the error message should be self explanatory… :confused:

Hum.

Are you sure that the objected you collided with has an instance of PlayerStateSync attached? You should add a simple guard statement to the top of your OnTriggerEnter method,

void OnTriggerEnter (Collider col)
{
  var target = col.gameObject;
  var com = target.GetComponent<PlayerStateSync>();

  if (com == null)
  {
    Debug.Log("Doesn't have PlayerStateSync attached");
    return;
  }

  // Everything else here 
}