- Home /
How can customize which prefabs are instantiated in a grid?
I'm trying to instantiate a prefab in a grid, and at certain coordinates in the grid I want to use a different prefab. For example I could generate the grid, but at 7,9 I could use the GameObject GrassHex instead of WaterHex.
The idea is that I can create a variable that randomly generates those coordinates, and then I can create a radius around that point. All objects in the grid within that radius will use a different prefab. This will create a "landmass" of GrassHex objects in the grid. Right now I have this script (this isn't the whole thing, just the instantiate part), and it generates the grid just fine, but it only uses one prefab.
WaterHex is the main hex prefab
gridHeightInHexes and gridWidthInHexes are public variables defined in the inspector (later on defined in game)
How can I define which points on the grid use a particular prefab?
void createGrid()
{
GameObject hexGridGO = new GameObject("HexGrid");
for (float y = 0; y < gridHeightInHexes; y++)
{
for (float x = 0; x < gridWidthInHexes; x++)
{
GameObject hex = (GameObject)Instantiate(WaterHex);
//Current position in grid
Vector2 gridPos = new Vector2(x, y);
hex.transform.position = calcWorldCoord(gridPos);
hex.transform.parent = hexGridGO.transform;
}
}
}
Here is an example of what I get now, and here is a basic example of what I want to get.
Answer by Chronos-L · Mar 17, 2013 at 02:19 AM
I propose the following solution.
GetPrefab Function
public static int WATER_HEX = 0, GRASS_HEX = 1 ..... METAL_HEX = 11;
GameObject GetHex( int id ) {
switch( id ) {
case WATER_HEX:
return waterHexPrefab;
case ...
....
}
}
You can use this in 2 ways:
GameObject hex = Instantiate( GetHex(WATER_HEX) ) as GameObject;
. Gives you controls on what you want to create.GameObject hex = Instantiate( GetHex( Random.Range(0,12) ) ) as GameObject;
. Randomize the hex.
I am using int
here, so that the function can use Random
. But I am quite sure that you can use Random
with enum
, but that needs a little bit more work.
Pros: Can do random generation and controlled generation
Cons: The switch in the function will become larger when you have more distinct hextiles.
To get a specific shapes, the only way I can think of is to use an array to store the formation. Something like this:
int w = WATER_HEX , g = GRASS_HEX;
int [][] formation =
{
{ w, w, w, w, w, w, w, w },
{ w, w, w, w, g, g, w, w },
{ w, w, w, g, g, g, w, w },
{ w, w, w, w, g, g, w, w },
{ w, w, w, w, w, w, w, w }
};
You can then combine it with the above function:
GameObject hex = Instantiate( GetHex( formation[x][y] ) ) as GameObject;
Your answer
Follow this Question
Related Questions
How to instantiate a prefab at mouse pos 1 Answer
Tiles Slow Down Game 0 Answers