How to increase and decrease object scale over time?

Hi everyone,

I’m trying to set up a scene where a pair of lungs are mimicking the process of breathing by increasing and decreasing their scale. What I want to do is increase the scale for 2 seconds and then decrease for 2 seconds and have this on some form of loop. Does that make sense?
I know it has something to do with transform.localscale, but can’t seem to get the timing right for c#.

Any help would be great!

Thanks so much :slight_smile:

4 Answers

4

You can use this code for more smooth animation:

private float _currentScale = InitScale;
private const float TargetScale = 1.1f;
private const float InitScale = 1f;
private const int FramesCount = 100;
private const float AnimationTimeSeconds = 2;
private float _deltaTime = AnimationTimeSeconds/FramesCount;
private float _dx = (TargetScale - InitScale)/FramesCount;
private bool _upScale = true;
private IEnumerator Breath()
{
    while (true)
    {
        while (_upScale)
        {
            _currentScale += _dx;
            if (_currentScale > TargetScale)
            {
                _upScale = false;
                _currentScale = TargetScale;
            }
            Lungs.localScale = Vector3.one * _currentScale;
            yield return new WaitForSeconds(_deltaTime);
        }

        while (!_upScale)
        {
            _currentScale -= _dx;
            if (_currentScale < InitScale)
            {
                _upScale = true;
                _currentScale = InitScale;
            }
            Lungs.localScale = Vector3.one * _currentScale;
            yield return new WaitForSeconds(_deltaTime);
        }
    }
}

private void Start()
{
    StartCoroutine(Breath());
}

Alternatively, you can create Animation with Mecanim Animation System, but it can be more complicate for you.

That's brilliant! Is there anyway to use this script and only affect the x and y axes? Keeping the z value at 1f the entire time?

–

No, is should have been [fixed in 5.1.3 release][1] so later versions should have it. OS X: Fixed building on OS X El Capitan. However you report issues not related to building. The fix specifically states building. Sounds like you got a different issue. [1]: https://unity3d.com/unity/whats-new/unity-5.1.3

–

A Coroutine suits well for this purpose, if you need to implement that with a script and want the lungs to resize over time.
Another way could be an animation which would probably look much nicer.

But here’s a basic script, attach it to your gameObject and do not forget to set the public variables in the inspector (or make them private and assign a default value).
This script assumes you’re having a default scale of (1,1,1)

  • maxsize determines the max. scale
  • growFactor determine how fast it will scale, you could implement another float for breathing out faster if you want to
  • waitTime will make the lung wait between breathing in and breathing out.

(A small hint: if you don’t need the default collider which is attached to the object, remove it as this needs some extra performance)

public class NewBehaviourScript : MonoBehaviour
{
    public float maxSize;
    public float growFactor;
    public float waitTime;

    void Start()
    {
        StartCoroutine(Scale());
    }

    IEnumerator Scale()
    {
        float timer = 0;

        while(true) // this could also be a condition indicating "alive or dead"
        {
            // we scale all axis, so they will have the same value, 
            // so we can work with a float instead of comparing vectors
            while(maxSize > transform.localScale.x)
            {
                timer += Time.deltaTime;
                transform.localScale += new Vector3(1, 1, 1) * Time.deltaTime * growFactor;
                yield return null;
            }
            // reset the timer

            yield return new WaitForSeconds(waitTime);

            timer = 0;
            while(1 < transform.localScale.x)
            {
                timer += Time.deltaTime;
                transform.localScale -= new Vector3(1, 1, 1) * Time.deltaTime * growFactor;
                yield return null;
            }

            timer = 0;
            yield return new WaitForSeconds(waitTime);
        }
    }
}

Thank You So Much worked totally fine

–

I not Understood maxSize is Vector3 or flot

–

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scale : MonoBehaviour {

private int toggle;

void Start () {
    toggle = 1;

}

// Update is called once per frame
void FixedUpdate () {

    if (toggle >= 0 && toggle <= 100)
    {
        toggle += 1;
        transform.localScale += new Vector3(1, 1, 0);
    }
    else if (toggle < 0)
    {
        toggle += 1;
        transform.localScale -= new Vector3(1, 1, 0);
    }
    else {
        toggle = -100;
    }
}

}

This will get you going.
Create a cube and assign this script, then change the value from inspector while in play mode, you will see the cube will scale in all axis appropriately.

public class PrototypeScaler : MonoBehaviour {

	public float value = 1f; //1 by default in inspector

	//This method is executed every frame
	private void Update(){
		//we store scale of this transform in temporary variable
		Vector3 temp = transform.localScale; 

		//We change the values for this saved variable (not actual transform scale)
		temp.x = value;
		temp.y = value;
		temp.z = value;

		//We assign temp variable back to transform scale
		transform.localScale = temp;
	}
}

The storing in temporary variable is needed because you can’t edit axis directly in c#, like transform.localScale.x = 2f is not allowed.

I tried that but it didn't quite work. Maybe because of newer version of Unity. Here is what I came up with to make a simple scaling over time, maybe it helps someone. public float scalingFactor = 1.1f; void Update () { transform.localScale = new Vector3(transform.localScale.x+transform.localScale.xscalingFactorTime.deltaTime, transform.localScale.y+transform.localScale.yscalingFactor * Time.deltaTime, transform.localScale.z+transform.localScale.zscalingFactor * Time.deltaTime); }

–