Graphics Reference
In-Depth Information
4.8 Automatic Self-Destruction Script
The main use for a script that automatically destroys its gameObject will be for special
effects. Particle effects such as explosions will be instantiated, their effect will play out, and
then they need to be destroyed.
In the example games, a short and simple class called AutomaticDestroyObject is
attached to a gameObject. After a set amount of time, set in the Unity editor Inspector
window, the gameObject is destroyed along with any associated child objects attached to
it.
Below is the full script:
public class AutomaticDestroyObject : MonoBehavior
{
public float timeBeforeObjectDestroys;
void Start () {
// the function destroyGO() will be called in
// timeBeforeObjectDestroys seconds
Invoke("DestroyGO",timeBeforeObjectDestroys);
}
void DestroyGO () {
// destroy this gameObject
Destroy(gameObject);
}
}
4.8.1 Script Breakdown
The class, which derives from MonoBehavior, is very simple. It uses Invoke to schedule a
call to the DestroyGO() function at a time set by the public variable timeBeforeObjectDe-
stroys. It probably goes without saying that DestroyGO() takes care of destroying itself,
with Destroy(gameObject).
4.9 Automatic Object Spinner
One common action you may need to do is spin an object. This may be for a number of
reasons, the most obvious (in this topic, at least) being to draw attention to power-ups in
the Interstellar Paranoids game. By spinning the power-ups, they are more obvious to the
player as something that may be interacted with, whereas static power-ups may be easily
missed or ignored.
Making an object spin in Unity may be very simple, but having a script to take care of
this is a useful little tool to keep in the toolkit.
Below is the script in full:
using UnityEngine;
using System.Collections;
Search WWH ::




Custom Search