How to change scale of a GameObject in unity by C# in runtime

 Transform component of a gameObject contains its position, rotation, and scale relative to its parent. We can change size of a gameObject by changing transform.localScale property. here are few ways of changing size by C# script.

scale of a GameObject in unity


By changing localScale

An example of changing scale a gameObject named "MyObject" to (2, 2, 2) is given below:

Code :
GameObject MyObject;

void Start()
{
    MyObject = GameObject.Find("MyObject");
    MyObject.transform.localScale = new Vector3(2, 2, 2);
}

here first we declare a MyObject of type GameObject and we set to reference by our desired object in start method by GameObject.Find("MyObject") method then change scale by MyObject.transform.localScale = new Vector3(2, 2, 2);


Coroutine Method

If we want to change size of a gameObject over time then we can use a Coroutine or Lerp function. An example coroutine for increasing scale of gameObject by every 0.1 second is given below:

Code :
IEnumerator ScaleOverTime()
{
    while (MyObject.transform.localScale.x < 2)
    {
        MyObject.transform.localScale += new Vector3(0.1f, 0.1f, 0.1f);
        yield return new WaitForSeconds(1);
    }
}

After that we can use StartCoroutine() to call this coroutine method

Code :
StartCoroutine(ScaleOverTime());

By using Vector3.Lerp

We can also use Vector3.Lerp() method to change scale of a gameObject with time. An example code is given below:

Code :
void Update()
{
    MyObject.transform.localScale = Vector3.Lerp(MyObject.transform.localScale, new Vector3(2, 2, 2), Time.deltaTime);
}

You can change scale of a gameObject by changing transform.localScale property. You can change scale across all three axis at once or one at each time.You can also use transform.localScale.xtransform.localScale.ytransform.localScale.z to change scale at perticular axis.  


Comments