0

This script is attached to the object I want to scale to 0,0,0 It's just not doing anything to the object it's attached to. No errors or exceptions just does nothing.

The maxSize in this case is 4,3,0.2 The minSize is 0,0,0

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

public class Scale : MonoBehaviour
{
    public GameObject objectToScale;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;
    public bool scalingHasFinished = false;

    private void Start()
    {
        objectToScale.transform.localScale = maxSize;
        scaleOverTime();
    }

    private void Update()
    {

    }

    public IEnumerator scaleOverTime()
    {
        float counter = 0;
        Vector3 startScaleSize = objectToScale.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            objectToScale.transform.localScale = Vector3.Lerp(startScaleSize, minSize, counter / duration);

            yield return new WaitForSeconds(duration);
        }

        scalingHasFinished = true;
    }
}

The main goal is to squeeze the object from all size to 0,0,0 like a magic effect making the object disappear slowly.

Dubi Duboni
  • 813
  • 2
  • 17
  • 33

2 Answers2

2

You could just modify your Coroutine in following way

IEnumerator ScaleDownAnimation(float time)
    {
        float i = 0;
        float rate = 1 / time;

        Vector3 fromScale = transform.localScale;
        Vector3 toScale = Vector3.zero;
        while (i<1)
        {
            i += Time.deltaTime * rate;
            transform.localScale = Vector3.Lerp(fromScale, toScale, i);
            yield return 0;
        }
    }

here you could just pass time to this Coroutine

So Here you can call this Coroutine from Start() as

StartCoroutine(ScaleDownAnimation(1.0f));

So, in this case, it will take exactly 1 second to scale down to Vector3.zero from its initial scale.

I recommend using AnimationCurve for smoother animations

You could Declare public AnimationCurve curve in your script and modify that curve from the inspector.

now modify the Code transform.localScale = Vector3.Lerp(fromScale, toScale, i); to transform.localScale = Vector3.Lerp(fromScale, toScale, curve.Evaluate(i));

I am quite sure you will get the desired result.

1

You're not calling the scaleOverTime function. Since it is of type IEnumerator you need to call it as a coroutine using StartCoroutine(scaleOverTime())

from the coroutine docs:

It is essentially a function declared with a return type of IEnumerator and with the yield return statement included somewhere in the body. The yield return line is the point at which execution will pause and be resumed the following frame. To set a coroutine running, you need to use the StartCoroutine function:

Remy
  • 4,843
  • 5
  • 30
  • 60