Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved How to Make GameObject Gradually Decrease in Size

Discussion in 'Scripting' started by cvionis, Jan 5, 2021.

  1. cvionis

    cvionis

    Joined:
    Dec 23, 2020
    Posts:
    6
    For my mobile game project, I need one of my game objects to gradually decrease in size immediately after the screen is pressed. I've tried using linear interpolation to change the scale of the object, but this made the object shrink extremely fast, and I wasn't able to adjust how quickly it shrank.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,931
    Linear interpolation of localScale is indeed the way to do this. Here's a simple example:
    Code (CSharp):
    1. public class Shrinker : MonoBehaviour {
    2.   // Time it takes in seconds to shrink from starting scale to target scale.
    3.   public float ShrinkDuration = 5f;
    4.  
    5.   // The target scale
    6.   public Vector3 TargetScale = Vector3.one * .5f;
    7.  
    8.   // The starting scale
    9.   Vector3 startScale;
    10.  
    11.   // T is our interpolant for our linear interpolation.
    12.   float t = 0;
    13.  
    14.   void OnEnable() {
    15.     // initialize stuff in OnEnable
    16.     startScale = transform.localScale;
    17.     t = 0;
    18.   }
    19.  
    20.   void Update() {
    21.     // Divide deltaTime by the duration to stretch out the time it takes for t to go from 0 to 1.
    22.     t += Time.deltaTime / ShrinkDuration;
    23.  
    24.     // Lerp wants the third parameter to go from 0 to 1 over time. 't' will do that for us.
    25.     Vector3 newScale = Vector3.Lerp(startScale, TargetScale, t);
    26.     transform.localScale = newScale;
    27.  
    28.     // We're done! We can disable this component to save resources.
    29.     if (t > 1) {
    30.       enabled = false;
    31.     }
    32.   }
    33. }
    Just set the ShrinkDuration and TargetScale to whatever you want.
     
    Phobos10 and MasterBro_Network like this.
  3. cvionis

    cvionis

    Joined:
    Dec 23, 2020
    Posts:
    6