How do I Scale a GameObject over time?

I’ve managed to get my gameobject to scale, but I would like to scale it bigger over the course of lets say 1 second but I don’t know how to do that since I’m extremely new at scripting. Here’s my code

public class Enlarger : MonoBehaviour {

public GameObject Player;

void OnTriggerEnter(Collider other)
{
	
	print("Collision detected with trigger object " + other.name);
	PlayerComponent playerComponent = other.gameObject.GetComponent<PlayerComponent> ();
	//checking if collided with player
	if (playerComponent) {
		Player.transform.localScale = new Vector3(2.0f, 2.0f, 2.0f);
		Destroy (gameObject);
	}
}

}

Any and all help is very welcome.

2 Answers

2

You could do it using coroutines and Vector3.Lerp

public class Enlarger : MonoBehaviour {

	public GameObject Player;

	void OnTriggerEnter(Collider other)
	{
		print("Collision detected with trigger object " + other.name);
		PlayerComponent playerComponent = other.gameObject.GetComponent<PlayerComponent> ();
		
		//checking if collided with player
		if (playerComponent) {
			StartCoroutine(ScaleOverTime(1));
		}
	}
	
	IEnumerator ScaleOverTime(float time)
	{
		Vector3 originalScale = Player.transform.localScale;
		Vector3 destinationScale = new Vector3(2.0f, 2.0f, 2.0f);
		
		float currentTime = 0.0f;
		
		do
		{
			Player.transform.localScale = Vector3.Lerp(originalScale, destinationScale, currentTime / time);
			currentTime += Time.deltaTime;
			yield return null;
		} while (currentTime <= time);
		
		Destroy(gameObject);
	}
}

This way it will throw a coroutine that will scale the player object frame per frame over time until it gets to its desired scale.

Thank you very much it works like a train. I used lerp before but it never occurred to me to use it in an if function. Lots to learn for me but thanks for helping me out. Sorry for my lack of knowledge lol I'm very new to this

please mark this answer has a resolution to your problem

I have a YouTube video about this - YouTube it only requires a few lines of code