- Home /
Question by
Fox-Handler · Jun 17, 2014 at 05:35 AM ·
instantiatecloned
Destroying the cloned gameObject
How could I find the name of the cloned gameObject that is instantiated so I can destroy it after a certain amount of seconds?
using UnityEngine;
using System.Collections;
public class Entity : MonoBehaviour
{
public float health;
public GameObject ragdoll;
public void TakeDamage(float dmg)
{
health -= dmg;
if (health <= 0)
{
Die();
}
}
public void Die()
{
Ragdoll R = (Instantiate (ragdoll, transform.position, transform.rotation) as GameObject).GetComponent<Ragdoll>();
R.CopyPose (transform);
Destroy (this.gameObject);
}
}
Comment
Best Answer
Answer by Nick4 · Jun 17, 2014 at 05:44 AM
public void Die()
{
GameObject obj = (GameObject) (Instantiate (ragdoll, transform.position, transform.rotation));
Ragdoll R = obj.GetComponent<Ragdoll>();
// Other stuffs to do when your character dies
}
You simply assign it to a variable. obj here is your instantiated game object.
Answer by rutter · Jun 17, 2014 at 05:43 AM
You already have a reference to the new Rigidbody, R
. You could keep that in a collection (an array, list, or whatever), so that you'll be able to access it later. Or, you could attach a component that helps keep track of and manage it. Plenty of behaviors can be achieved with simple custom components.
In the specific case of Destroy
, though, there's an optional second parameter specifying a delay in seconds:
//destroy R in 5 seconds
Destroy(R, 5);