1
\$\begingroup\$

I have simple emmiter which sending enemies toward player in center of screen. Player can shoot missile (also emmiter). I want to destroy enemy AND missile in same time.

Here is my code attached to Enemy

 public GameObject player;
 public GameObject missile;

 void OnTriggerEnter2D(Collider2D collider)
 {
     if (collider.gameObject.name == player.name)
     {
         Destroy(gameObject);
         Application.LoadLevel("Retry");
     }

     if (collider.gameObject.tag == missile.tag)
     {
         Destroy(gameObject);
         Destroy(missile.gameObject);
         Score.killed++;
     }
 }

But after missile hit enemy, error in unity occur

Destroying assets is not permitted to avoid data loss.

Well... im programmer but new in unity. So my question is not that simple : i think im destroying object which is still in use. Am i right? How can i destroy both objects? When i can destroy GameObject? I tried to use this

GameObject mssle = Istantiate(missile,missile.transform.position,Quaternion.identity);
Destroy(mssle);

as was suggested by good people on unityanswers. Didnt work, missile is stil alive and my answer got rejected. Am i destroying whole prefab or what? This is little confusing for me

\$\endgroup\$
2
  • \$\begingroup\$ Sounds to me like you're trying to destroy an object in the scene( while not playing the game ) or a prefab. \$\endgroup\$
    – Ben
    May 7, 2015 at 8:59
  • \$\begingroup\$ well i think im doing something wrong. But really i dont know what and cant get suitable answer or even discussion from unityanswers. Only rejection \$\endgroup\$
    – Bob T.
    May 7, 2015 at 9:10

1 Answer 1

1
\$\begingroup\$

I assume you assign a Prefab to public GameObject missile in the inspector. When you try to destroy missile inside of your OnTriggerEnter2D method, the error message does make sense, since you're trying to destroy a prefab and not an instance.

Instead of trying to destroy missile, you should destroy the object that collided with your GameObject.

So, replace: Destroy(missile.gameObject); with: Destroy(collider.gameObject); (you can be sure to destroy a collided missile here, since you already checked the matching tag in your if statement: if (collider.gameObject.tag == missile.tag))

\$\endgroup\$
1
  • \$\begingroup\$ this is actually working! And you gave me excelent explanation why it was happening, i understand what was wron! Thanks much and i must say: blame unity community. Dont have rep here to upvote :( \$\endgroup\$
    – Bob T.
    May 7, 2015 at 9:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .