Slightly Increase GameObject Scale While GameObject Is Constantly Shrinking

Hello,

I’m currently using the following script to gradually shrink the scale of the player (a sphere) in my game:

  // Time it takes in seconds to shrink from starting scale to target scale.
  public float ShrinkDuration = 5f;

    // The target scale
    public Vector3 TargetScale = Vector3.one * .5f;

    // The starting scale
    Vector3 startScale;

    // T is our interpolant for our linear interpolation.
    float t = 0;

    void OnEnable()
    {
        startScale = transform.localScale;

        t = 0;
    }

    void Update()
    {
        t += Time.deltaTime / ShrinkDuration;

        Vector3 newScale = Vector3.Lerp(startScale, TargetScale, t);
        transform.localScale = newScale;

        if (t > 1)
        {
            enabled = false;
        }
    }

However, I also need to increase the scale of the player by a small amount every time it enters a certain trigger. Here is the code I currently have for doing so:

private void OnTriggerEnter(Collider trig)
    {
        GameObject.Find("PlayerBody").transform.localScale += new Vector3(2, 2, 2);
    }

The problem I am having is that the script making the player grow only works when the script making the player gradually shrink is removed from the player or disabled. How would I make the player gradually shrink but also make the scale of the player increase slightly when it enters a certain trigger?

I would keep a separate float that starts at 1.0 and goes down periodically, and then when you hit your trigger, increase it.

private float MyScaleFloat = 1.0f;

Then use that float every frame to set the size:

playerTransform.localScale = Vector3.one * MyScaleFloat;

EDIT: looking at your code above, the shrinking code is producing fresh scales from your min to max scale. This is why growing doesn’t work: you grown the .localScale and then it gets wiped out by the assignment from Lerp next frame.

I stand by my recommendation above: nothing in your code should do anything to scale, except that one assignment in my sample code. Everything else would hit the scale variable.

@Kurt-Dekker thanks for the help! I was eventually able to create a script using your suggestions to make the scaling work properly.

1 Like