简体   繁体   中英

How can I destroy a GameObject that I instantiate in Unity?

I have a code that spawns 2 GameObject that are clones of 2 prefabs, an enemy prefab, and a player prefab:

GameObject PlayerGO =player;
playerUnit = PlayerGO.GetComponent<Unit>();
Instantiate(player, PlayerStation);
GameObject EnemyGO = Instantiate(enemy, EnemyStation);
enemyUnit = EnemyGO.GetComponent<Unit>();

And the clones are called "PlayerGO" and "EnemyGO" respectively.

Now, the idea of the code is that when a battle starts, both the player and enemy spawn in their positions and engage in a fight, but, the problem comes when I enter another battle, because the enemy of the 1st battle is still there, and not only that, but now I have to players at the same time. I tried using this code:

Destroy(enemy);

To get rid of the object, but it only destroys the original instance of the enemy object, not the clone which is still in the hierarchy. I tried using Destroy(EnemyGO) but the code doesn't allow me to do so and suggests using "enemy" instead (which, doesn't work), I also tried with "Destroy(Instantiate(enemy, EnemyStation));", but that also didn't work

How can I destroy the clone?

In the prefab of the enemy, have a script that Destroys itself by haveing Destroy(gameObject) . If the enemy detects a collision then trigger the script. If you want the player to trigger the script then use yourGameobjectVariableToTheEnemy.GetComponent(SelfDestruct)().selfDestruct (the first SelfDesruct is the script name and the second is the function name).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM