- Home /
Instantiating Prefabs into an Array with Indexing
I'm drawing a room of public prefab cubes (that are actually made up of 6 Quads[Top, Bottom, Front, etc.]), each cube is 1x1x1 and the size of the room is 1 unit high on the Y value but the Z and X are determined by a public int input called roomsize (Ex. 64x64).
My goal here is to index these prefab cubes as they are drawn in so I can reference them later in Raycasting. For example, if I want to select the "Top" quad of "prefabCube_[index]" I can simply make a hit.collider.prefabCube_1.Top, or something-like-that.
I've kind of hit a wall, I'm not unfamiliar with C# but I am new to Unity. Can anyone point me in the right direction?
Code Below:
public class createCube : MonoBehaviour {
public GameObject prefab;
public int roomSize;
// Use this for initialization
void Start () {
for (int i = (-1*roomSize); i < roomSize; i++) {
for (int j = (-1*roomSize); j < roomSize; j++) {
GameObject tileMap = Instantiate(prefab, new Vector3(i, 0, j), Quaternion.identity) as GameObject;
}
}
}
Answer by Mmmpies · Feb 05, 2015 at 08:12 PM
This is what I do for menu items when I want to dynamically create spell menus. I use one scroll panel and instantiate different types of spell so I store the instantiated in a list so I can destroy the old ones when the menu changes:
private List<GameObject> localMenuItemList = new List<GameObject>();
// then when I instantiate
GameObject newItem = Instantiate(itemPrefab) as GameObject;
// I edit the properties of that prefab to fit the spells
// when all that's done I add to the List
localMenuItemList.Add(newItem);
// when I want to clear the list:
if(localMenuItemList.Count > 0)
{
for(int i = 0; i < localMenuItemList.Count; i++)
{
Destroy(localMenuItemList[i]);
}
}
localMenuItemList.Clear();
Oh almost forgot, you need:
using System.Collections.Generic;
To use Lists