Arrays and Colliders

I am encountering a “NullReferenceException: Object reference not set to an instance of an object” error when this code is triggered:

var touchingObjects : Array;

function OnTriggerEnter(other : Collider) {
	print(other);
	touchingObjects.Push(other);
	
	if (!transform.parent.GetComponent(PlayerMovementScript).grounded) {
		transform.parent.GetComponent(PlayerMovementScript).grounded = true;
	}
}

Any ideas? If I do a print(object); inside that function is claims that it is present.

The null is other. What are you using that for?

that script is applied to a player “foot” object to see if it is touching anything and what it is touching.

Why would other be null if the function is, by definition, triggered because it is not null?

Have you defined other earlier in the script?

Yes… the part between the parenthesis for the OnTriggerEnter function:

function OnTriggerEnter(other : Collider) {

It takes the Collider data that is passed to the function and puts it in a function-specific variable called “other”

You’ve got to define other as a variable, and then go from there. I’ll help on this script and maybe more if you like.

I’m pretty sure it is defined as a variable right there. It is defined as a variable called “other” of type “Collider”

Oh I overlooked your 1st variable. touchingObjects should be defined as a transform or a GameObject. Then further define it.

Here’s an example:

var touchingObjects : GameObject[];
var touchingObjects : GameObject[].FindGameObjectsWithTag("Touching Objects");

touchingObjects is an array, not a GameObject or Transform.

Anyway, it turns out the array was the null. I had to set it equal to a new Array() like this:

var touchingObjects : Array = new Array();

That fixed it, so now the code looks like this:

var touchingObjects : Array = new Array();

function OnTriggerEnter(other : Collider) {
	print(other);
	touchingObjects.Push(other);
	
	if (!transform.parent.GetComponent(PlayerMovementScript).grounded) {
		transform.parent.GetComponent(PlayerMovementScript).grounded = true;
	}
}

For some reason it didn’t occur to me that Unity doesn’t auto-assign an empty array list to newly defined arrays. That’s what too much user-friendliness can do to you :stuck_out_tongue:

Thanks for helping me rexamine this whole thing :smile: