I'm a total Unity beginner, and I was wondering how to remove a clone when a new one is instantiated. I want to create a platform under the player when he jumps and the fire button is pressed, but I want the previous platform I created to disappear. Here's my code:
var prefab : Transform;
function Update () {
var controller : CharacterController = GetComponent(CharacterController);
if (!controller.isGrounded) {
if (Input.GetButtonDown ("Fire1")) {
Instantiate (prefab,
GameObject.Find("Player").transform.position,
Quaternion.identity);
}
}
}
You need to store a reference to the prefab when you created it. Then you destroy that object before creating a new one (and storing it again). You also need to 'null' check to ensure that it exists (as it won't the first time).
var prefab : Transform;
private var platform : Transform;
function Update ()
{
var controller : CharacterController = GetComponent(CharacterController);
if (!controller.isGrounded)
{
if (Input.GetButtonDown ("Fire1"))
{
if ( platform != null ) // does a platform exist
Destroy(platform.gameObject); // destroy the platform
platform = Instantiate (prefab, GameObject.Find("Player").transform.position, Quaternion.identity);
}
}
}
Let me know if any of this is unclear (or doesn't work - it's untested)