- Home /
AddComponent deletes the game object.
This should work right?
void Awake()
{
if(Type == WeaponType.Projectile)
{
gameObject.AddComponent<BallisticProjectile>();
}
}
Instead it deletes the weapon. What am I doing wrong?
You sure this is what removes the gameobject? Could be that it replaces gameObject to become the component or a new gameobject with the component. But seems weird.
Try just: AddComponent();
Editied comment does not update for me, here is what I meant to try:
AddComponent<BallisticProjectile>();
There is no definition for plain AddComponent. There is AddComponent$$anonymous$$enu. You have to specify where you want that component added, in my case it's the game object that has the script. Unfortunately it disappears at runtime.
Also I'm pretty sure that this is what removes the object, since this is the only line of code that does anything.
Does your BallisticProjectile script destroy the GameObject it's on(as in Destroy(gameObject))? Could be triggering self-destruction immedialetly
Omg yes I can't believe I missed it. It has a public float lifetime but it's not initialized by default. Thanks.
Answer by Wisearn · Nov 17, 2014 at 08:24 AM
The issue resides either in "BallisticProjectile" script or in other parts of the code not posted here.
BallisticProjectile had Destroy with a public float lifetime. It didn't have a default so it was 0. Fixed it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613171701im_/https://answers.unity.com/themes/thub/images/avi.jpg)