Search Unity

Question Scaling overtime

Discussion in 'Scripting' started by MrPuppyy, Sep 25, 2020.

  1. MrPuppyy

    MrPuppyy

    Joined:
    Nov 4, 2019
    Posts:
    40
    So I got the rescale script, but i'm not quite sure how to make it rescale over time. Like over the timespan of a minuet, it slowly grows the X coordinate to let's say 10, so it goes from 1 or whatever and overtime grows to 10. Script is:

    Code (CSharp):
    1.   bool resized = false;
    2.     void Update()
    3.     {
    4.         if (Input.GetKey("f") && resized == false)  // If the player is pressing the "f" key
    5.         {
    6.             Vector3 CurrentScale = transform.localScale;
    7.             Vector3 newScale = CurrentScale + new Vector3(0, 0, -0.4f);
    8.             transform.localScale = newScale;
    9.             resized = true;
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Coroutines are best for this. Here's an example:
    Code (csharp):
    1.  
    2. if (..) {
    3. StartCoroutine(ScaleOverTime(transform.localScale, transform.localScale + new Vector3(0f,0f,-0.4f), 60f));
    4. }
    5.  
    6. .....
    7.  
    8. private IEnumerator ScaleOverTime(Vector3 startScale, Vector3 endScale, float duration) {
    9. for (float t = 0f; t < duration; t += Time.deltaTime) {
    10. float lerpValue = t / duration;
    11. transform.localScale = Vector3.Lerp(startScale, endScale, lerpValue);
    12. yield return 0;
    13. }
    14. transform.localScale = endScale;
    15. }
     
    Joe-Censored and PraetorBlue like this.