- Home /
Create an array of gameobjects in trigger?
I'm trying to create an array and keep it updated based on what objects are currently in a trigger. Here is what I have so far, the problem is that I am getting a null reference error when sending objEntering.gameObject to the augmentArray function.
function OnTriggerEnter(objectEntering : Collider) { objectsInTrigger++; augmentArray(objectEntering.gameObject, fishInRange); Debug.Log("Object name : " + objectEntering.gameObject); Debug.Log("Obj in trigger " + objectsInTrigger);
}
function augmentArray(objToAdd : GameObject , array : GameObject[]) { var tempArray = new GameObject[array.length+1];
for(i = 0; i < array.length; i++)
tempArray[i] = array[i];
tempArray[array.length+1] = objToAdd;
// Refill the original array etc etc
}
Answer by Statement · Mar 13, 2011 at 09:13 PM
I don't know any null reference problems (unless your array is null to begin with) but I see you're indexing out of range here:
tempArray[array.length+1] = objToAdd;
Did you mean:
tempArray[array.length] = objToAdd;
You might want to use a List.<GameObject>
instead, it supports adding new items to it so theres no need creating copies of arrays.
import System.Collections.Generic;
// I am no JS guru so you might be able to strip off the new keyword also. var fishInRange : List.<GameObject> = new List.<GameObject>();
function OnTriggerEnter(objectEntering : Collider) {
objectsInTrigger++; // OR you could use fishInRange.Count fishInRange.Add(objectEntering.gameObject); Debug.Log("Object name : " + objectEntering.gameObject); Debug.Log("Obj in trigger " + objectsInTrigger); }
I'd been intentionally avoiding list and js arrays due to performance issues, along with the issue of (in my experience) spotty performance on the iPhone/iPad. However, you were correct in the index out of range error. oops. It's working as intended now, thanks.
I don't know about performance issues on iPhone/iPad, to me it just sounds a bit odd, however the access times aren't that much of a deal. See this topic about it, it's quite interesting: http://answers.unity3d.com/questions/32048/is-listt-as-fast-to-access-as-a-standard-array/32068#32068 however, allocating a new array each time you want to add something surely must be one of the most inefficient ways to go about.
That was a very helpful post indeed. I think I may just scrap this whole bit and utilize a list.
@karl: there are no performance issues with List. Avoid JS Array, yes.
If you are concerned about performance you can try to avoid dynamic typing also. Read more here: http://unity3d.com/support/documentation/ScriptReference/index.Performance_Optimization.html