Friday, April 25, 2014

Update 32: Decaying objects

I wrote a class today that I add to components I want to remove from the game (for example, my destructed walls). 

I add it to a gameobject like this: (where character is a gameObject)

            character.AddComponent<DynamicExplosionPiece>();

In the "Awake" method of this class, it randomly generates a number between 0 and 10, which is the number of seconds in the game before the object dies. What this means, is when I create 100 little objects for my destructed object, the game cleans them up after 10 seconds - at the most!. Because it's random, it has a decay effect. Here is a screenshot, of a recently dead enemy (red) tank. The turret has decayed, the cannon has not, and about 25% of the square body has decayed.



The actual class is here:

using UnityEngine;
using System.Collections;

public class DynamicExplosionPiece : MonoBehaviour
{
    void Awake()
    {
        StartCoroutine(StartTimerBeforeDestruction(Utility.GenerateRandomNumber(0, 10)));
    }

    private IEnumerator StartTimerBeforeDestruction(float time)
    {
        yield return StartCoroutine(Wait(time));
        Destroy(this.gameObject);
    }

    private IEnumerator Wait(float time)
    {
        yield return new WaitForSeconds(time);
    }
}

1 comment: