Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a gameobject to an exact length in unity

Tags:

c#

unity3d

In Unity I have a float that represents a distance

float distance = Vector3.Distance(start.position,end.position);

I want to use that float to change the size of an object along its Z axis. I tried:

gameobject.transform.localScale.z = distance;

However, this just changes the scale, I need to change the game object to an exact length. Is there a straightforward way to achieve this?

like image 793
Chris Headleand Avatar asked Jul 28 '15 05:07

Chris Headleand


People also ask

What is a static GameObject?

If a GameObject does not move at runtime, it is known as a static GameObject. If a GameObject moves at runtime, it is known as a dynamic GameObject. Many systems in Unity can precompute information about static GameObjects in the Editor.

How do you set a GameObject position in Unity?

You can change the object position in the code by manipulating the transform property of the object. transform. position = new Vector3(1.0f, 1.0f, 1.0f); Simple as that!


2 Answers

I created a workaround function to convert a specific length into a scale (for anyone who may find this question in the future). Game objects can only have their size changed though scale, but their exact size can be found through the renderer. using a little interpolation you can convert this into a new scale to resize your object to an exact size.

public void newScale(GameObject theGameObject, float newSize) {

    float size = theGameObject.GetComponent<Renderer> ().bounds.size.y;

    Vector3 rescale = theGameObject.transform.localScale;

    rescale.y = newSize * rescale.y / size;

    theGameObject.transform.localScale = rescale;

}
like image 51
Chris Headleand Avatar answered Sep 23 '22 17:09

Chris Headleand


Unity has no thing like "Length" for any object. At the scale of (1,1,1) unity considers that every object is of one unit. meaning if you want your object to be 3 units long along z axis you change its scale to (1,1,3) and similarly for other axis. thats why it is said that you need to take special care while designing assets for unity as they all need to made according to unity defined scale.

like image 44
Anas iqbal Avatar answered Sep 23 '22 17:09

Anas iqbal