Reputation: 477
I want to create a hexagon grid. I Have a 3D model which I made in blender with some dimensions.
I have a script in Unity which is supposed to generate a hex grid with a given hexagon.
The model of the hex is placed in a Prefab. I need the size "Real size not the scale" of that prefab in order to generate the grid.
How can I get the size of the model which is in a prefab.
public class GameWorld : MonoBehaviour
{
// Fields
public GameObject HexPrefab;
// Size of the map in terms of number of the objects
// This is not representative of the actual size of the map in units
public int Width = 20;
public int Height = 20;
void Start()
{
MeshRenderer[] asd = HexPrefab.GetComponentsInChildren<MeshRenderer>();
var a = asd[0].bounds;
Debug.Log(string.Format("x: - {0:f3}", a.size.x));
Debug.Log(string.Format("y: - {0:f3}", a.size.y));
Debug.Log(string.Format("z: - {0:f3}", a.size.z));
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < Height; y++)
{
Instantiate(HexPrefab, new Vector3(x, 0, y), Quaternion.identity);
}
}
}
void Update()
{
}
}
Here are the dimensions from blender.
I don't want to hard code it because I will need to use hexagons of different sizes in the future!
This code gives me a size of 0.
The prefab consists of only one model and nothing else.
Thank you in advance!
Upvotes: 1
Views: 5398
Reputation: 477
My Prefab Consists of only the model.
Here is what it looks like.
And this is the properties of the model:
Then in the code I did the following:
Mesh mesh = HexPrefab.GetComponentsInChildren<MeshFilter>()[0].sharedMesh;
And now I can get the dimensions of the mesh like this:
mesh.bounds.size
In my case the prefab has a scale of 1 so the size of the model and the size of the prefab are the same but if you want to go the extra step you can multiply the size that we got from the model by the scale of the prefab.
Hope this helps someone who is having the same question!
Have a nice day!
Upvotes: 2