Certainly! Below is a C# script for Unity that features a Shrink function, as you described. The script uses a coroutine to gradually shrink the GameObject over a specified duration (SecondsToShrink). Once the GameObject's scale reaches zero, it will be destroyed.
You can attach this script to any GameObject you wish to shrink. Make sure to set the SecondsToShrink parameter in the Unity Inspector.
using UnityEngine;
public class ShrinkAndDestroy : MonoBehaviour
{
[SerializeField]
private float SecondsToShrink = 2.0f; // Time in seconds to shrink to zero
// Call this function from elsewhere to start shrinking the GameObject
public void Shrink()
{
StartCoroutine(ShrinkCoroutine());
}
private IEnumerator ShrinkCoroutine()
{
Vector3 originalScale = transform.localScale;
Vector3 targetScale = Vector3.zero;
float elapsedTime = 0f;
while (elapsedTime < SecondsToShrink)
{
// Calculate the new scale based on the time elapsed
float t = elapsedTime / SecondsToShrink;
transform.localScale = Vector3.Lerp(originalScale, targetScale, t);
elapsedTime += Time.deltaTime;
yield return null; // Wait for the next frame
}
// Ensure the scale is exactly zero at the end
transform.localScale = targetScale;
// Destroy the GameObject once it has shrunk to its final size
Destroy(gameObject);
}
}
How to Use the Script
- Create a New Script: In Unity, create a new C# script named
ShrinkAndDestroy and copy the above code into it.
- Attach the Script: Attach this script to the GameObject you want to shrink in the Unity Inspector.
- Set SecondsToShrink: In the Inspector, you'll find the
SecondsToShrink variable where you can set the duration you want for the shrinking effect.
- Invoke Shrink: Call the
Shrink() method from any other script when you want to start the shrinking process. For example, you can call it in response to a user input or a collision event.
Example of Calling Shrink
Here is a simple example of how you could call the Shrink method from another script:
using UnityEngine;
public class ExampleTrigger : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Player")) // Check if the collider has the tag "Player"
{
ShrinkAndDestroy shrinkable = GetComponent<ShrinkAndDestroy>();
if (shrinkable != null)
{
shrinkable.Shrink(); // Call the Shrink function
}
}
}
}
Make sure to attach ExampleTrigger to the GameObject that will trigger the shrink effect (such as a collider) and set the appropriate tags in Unity.