- Home /
Cannot destroy instantiated objects
So i made a bullet which shoots forwards, but the bullet wont destroy itslef after a set amount of time. Can anyone tell me where i'm going worong?
Here's the code i'm currently using
var prefabBullet:Transform;
var shootForce:float;
var destroyTimeMin:float;
var destroyTimeMax:float;
function Update()
{
if(Input.GetButtonDown("Fire1"))
{
var instanceBullet = Instantiate(prefabBullet, transform.position, Quaternion.identity);
instanceBullet.rigidbody.AddForce(transform.forward * shootForce);
Destroy(instanceBullet, Random.Range(destroyTimeMin, destroyTimeMax));
}
}
Cheers
Answer by Leslie-Young · Jun 13, 2013 at 10:28 AM
I have a suspicious that since instanceBullet is a transform, you are trying to destroy the component, not the gameobject. I normally save prefabs as GameObjects, but if you do nto want to make thatchange then simply do...
Destroy(instanceBullet.gameObject, Random.Range(destroyTimeMin, destroyTimeMax));
or change it all to ..
var prefabBullet:GameObject;
var shootForce:float;
var destroyTimeMin:float;
var destroyTimeMax:float;
function Update()
{
if(Input.GetButtonDown("Fire1"))
{
var instanceBullet = Instantiate(prefabBullet, transform.position, Quaternion.identity);
instanceBullet.rigidbody.AddForce(transform.forward * shootForce);
Destroy(instanceBullet, Random.Range(destroyTimeMin, destroyTimeMax));
}
}
Answer by superscruf · Dec 17, 2018 at 05:52 AM
Hey - total newb here. One thing I noticed about the above solution - simply adding the "var newVariableName = " in front of [ye olde instantiation code] gives one a handle with which to manipulate the instantiated entity (not just Destroy(), any number of tweaks become available). I learned to instantiate stuff by simply using Instantiate(), so the "var =" bucket opened up a whole new world for me. Totally diggin' it!
Mo
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Destroy (Clone) 1 Answer
Issues with destroying a game object 2 Answers
OnCollisionEnter Stopped Working 1 Answer