- Home /
Array of Arrays of GameObjects/Prefabs (C#)
I'm trying to make a procedurally generated tiled map/object set. I have each square in the map (`int[,]`) store an index of the type of tile it is. Then, I want to be able to use this to randomly select from a set of prefabs to spawn the actual tile with Instantiate(). Furthermore, I want different types of tiles to have different types of these variants (e.g. a "grass" tile may have 2 or 3 variants, whereas a "house" tile would have 7-10 variants, each with its own model/child objects/particle systems).
Optimally, I'd like to have a GameObject[][]
, with the outer index being the tile type, and the inner index being randomly selected, like so (extra variables for clarity):
public GameObject[][] tilePrefabs;
void generateMap(int[,] map) {
System.Random r = new System.Random(seed);
//for every tile (loop through x and y):
int tileType = map[x,y];
int numVariants = tilePrefabs[tileType].length;
GameObject tileToAdd =
Instantiate(tilePregabs[tileType][r.Next(0,numVariants)]);
}
Problem is, I can't figure out a way to assign prefabs to either a GameObect[][]
or a GameObject[,]
through the editor. Is there a way around this, besides doing something like
GameObject[] tileType1;
GameObject[] tileType2;
...
and so on?
Thanks!
tl;dr: Any way to assign prefabs to an array of arrays or 2D array, preferably in the editor?
Answer by Siegeon · Dec 26, 2011 at 03:17 AM
What you are asking is a little confusing, but if you simply want to assign gameObjects to an array through the editor, create a
Public GameObject[] gameObjects
Then drag and drop your game objects to this array from through the editor. Creating a double array Public GameObject[][] gameObjects is a bit more difficult since you can't access it through the editor. You can still do this you will have to load the resources programmaticly. This is not hard to do but it does involve a little set up. First In your project pain create a Resources folder, put your gameObject in there. Finally create an enumerated type for which ever tile type/name is accounted for.
Then in your script you can load those resources specifically like so...
private GameObject[] TileGameObjects; public enum TileType { Rock, Grass, Wood, };
void Awake() { string[] names = Enum.GetNames(typeof(TileType)); for (int i = 0; i < names.Length; i++) { TileGameObjects[i] = Resources.Load(names[i]) as GameObject; } }
Your answer
Follow this Question
Related Questions
Prefab not loading in data from Inspector 1 Answer
Get Script from gameobject knowing only parent script 1 Answer
How to merge an arrays into arrays inside an array? 3 Answers
Prefabs instantiated from an array are keeping their public int value 1 Answer
Instantiating an array of objects - how can I instantiate a certain prefab only once? 1 Answer