Problem with Object Lifetime in Array?

Hi,
i have a serious problem i’m fighting since several days. my script (js) contains an array-variable which is filled in the start-function with some game objects (prefabs). when i try to reference the elements of that array in another function i always get a null-reference exception. first i thought it is a problem with 2d array which i found to be not supportet in js. but this problem also occurs in a 1d array. i have tried several ways and slowly my ideas are depleted. so i hope someone can give me a hint where my mistake is. note: i come from c++ and c# and use unity-script (resp java script) the first time. and i want to use javascript for several reasons so using c# is not really an option for me here.
thanks alot in advance.

var CubeGrid = new GameObject[10];// shall store the objects for fast reference
var tmpobj;
var prefab : Transform;// the prefab is filled in the inspector

function Start()
{
	for(var i : int = 0; i < 10; i++)
	{// create all objects in script
		tmpobj = Instantiate(prefab, Vector3(i*1.0,0.0,0.0), Quaternion.identity);
		tmpobj.name = String.Format("Object{0}",i);
		CubeGrid[i] = tmpobj as GameObject;
	}
}

function Move(objtomove : int)
{// this function is called from the onmouse event of the object which has stored a reference to this script
	var moveCube = CubeGrid[objtomove];	// exception is raised here, when i search the object with findobject() it works
	moveCube.transform.position.y += 1.1;
}

Don’t do things like “var tmpobj;”, since that uses dynamic typing, which you should avoid unless you have a good reason for using it. Specify the type, either explicitly or by using type inferencing. You don’t need that variable at all anyway; just do "cubeGrid = Instantiate(…".
–Eric

Your problem is actually in that temporary variable, even though it doesn’t seem temporary… What happens is that the variable creates the object, the references it to CubeGrid*, then destroys it, thus destroying the reference. The best concept is to create the object in the grid. (note the .gameObject at the end)*
* *for(var i : int = 0; i < 10; i++) {// create all objects in script CubeGrid[i] = Instantiate(prefab, Vector3(i*1.0,0.0,0.0), Quaternion.identity).gameObject; CubeGrid[i] = String.Format("Object{0}",i); }* *

that solved the problem. thanks alot.

In C# the object referenced in the Array would live als long there is at least one reference to it (the one in the array). so thats the behavior which i was wrong with. thanks alot. does someone have some guide or tutorial about object lifetime and scope in unityscript?

but i see such code like mine quite often. At least which stores the reference to an object returned from an array for often usage in a loop. so would it be safe to make tmpobj global? or after CubeGrid = Instantiate do tmpobj = CubeGrid*?*
_*

[quote]_
note the .gameObject at the end
_
[/quote]
*_
why that? it worked in before also. can you explain that please a bit?