Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting height/width from a unity gameobject

I'm working on a version of Conway's Game of Life in Unity, and here is my setup for making the grid:

I've created a prefab of an individual cell responding to mouse click that will be the basis for creating the cell grid. I have a Empty GameObject to act as the controller to create the grid. I'm putting it in the code for the controller like so, pointing my prefab to the field:

[SerializeField]
private GameObject Cell;

private Camera _camera;

My idea was to get the dimensions of the Cell and instantiate it into a grid, with _camera pointing to the Main camera to get boundaries. However, I'm not sure how to get the height/width from GameObject. What's the best way to find this out?

like image 501
foxjasond Avatar asked Oct 30 '15 22:10

foxjasond


People also ask

How do you find the width of an object in unity?

If your object has a renderer, you can use renderer. bounds. size , which will return a vector with the height and width (and depth, if it is in 3D).

How do you find the height and width of an image in unity?

You can get the width/height using RectTransform. rect. simply cast the transform to RectTransorm, GameObject mynewcard = (GameObject)Instantiate(card);

What is rect in unity?

Description. A 2D Rectangle defined by X and Y position, width and height. Unity uses a number of 2D coordinate spaces, most of which define X as increasing to the right, and Y increasing upwards. The one exception is in the GUI and GUILayout classes, where Y increases downwards.


1 Answers

I don't know if you found the answer, but the most common way is using Collider (if you have one, but mouse click needs it) or Renderer (if you have a mesh) by using:

GetComponent<Collider>().bounds.size
GetComponent<Renderer>().bounds.size

Game of life is very nice, I've written my paper for bachelor seminar about it. Have fun!

like image 81
Dommar92 Avatar answered Sep 20 '22 03:09

Dommar92