Multiple Instantiates

Hello,

Everything I know about Java programming I have learned from Unity. I had no previous knowledge of it whatsoever. Most of the terminology I can look up and comprehend thanks to the built-in manual and example projects, but when it comes to the actual basics, I am stumped.

So, here’s the thing.

How can I Instantiate multiple objects, of an amount defined by a variable, simultaneously?
And, seemingly more advanced, how can I at the same time access a script in the root transform of each of them at the same time?

Thank you.

Here’s one way of doing it:

var numObjects = 5;
var spacing = 1.0;
var prefab : YourScript;

private var yourScripts : YourScript[];

function CreateObjects()
{
	yourScripts = new YourScript[numObjects];
	for(var i = 0; i < numObjects; ++i)
	{
		yourScripts[i] = Instantiate(prefab, Vector3(i * spacing, 0, 0), Quaternion.identity);
	}
}

function DoSomethingWithObjects()
{
	// Call the Something function on each item in yourScripts:

	for(var yourScript in yourScripts)
	{
		yourScript.Something();
	}
}

In this example, I’m assuming that the prefab has a YourScript component on it. That will make it possible to drop it into the ‘prefab’ variable in the inspector. Instantiate always returns the same kind of object as you pass to it in the first parameter, so as I’m giving it a reference to the prefab’s YourScript, it will output a reference to the YourScript component on the newly created instance. I record that in an array as soon as it’s created so I can use it later on in the DoSomethingWithObjects() function.

See, it’s all those i:s and +:s I don’t get, from my lack of rudimentary understanding of Java. However, the code you provided was quickly and easily reworked to do exactly what I wanted! Thanks abundance. I wasn’t specific in what I wanted to do, but the answer held all the information I required.

To save you headache i nthe future:

JavaScript is not Java but something totally different. Its a pretty bad naming they (Netscape) used back then and did so mainly to missuse the hype around java for their own use.

In case of Unity JavaScript is not even the normal javascript but a JS like syntax on top of .NET