- Home /
How to save the destroyed state of an enemy ?
On Trigger enter the enemy get destroyed but every time I play the game the enemy get back. How to save the destroyed state of enemy so that the enemy wont get back ?
Answer by Llama_w_2Ls · Jan 25, 2021 at 02:31 PM
You would have to save a bool that contains data on whether the enemy was destroyed or not. You could try using PlayerPrefs for this. For example:
const string EnemySaveData = "WasDestroyed";
private void OnTriggerEnter(Collider other)
{
// Enemy was destroyed
Destroy(other.gameObject);
// Save this info
PlayerPrefs.SetString(EnemySaveData, "true");
}
And when you first hit play, you need to check if the enemy was destroyed last time:
private void Start()
{
string WasDestroyed = PlayerPrefs.GetString(EnemySaveData);
// Destroys enemy if they were destroyed
// previously
if (WasDestroyed == "true")
Destroy(gameObject);
}
it works but it destroy all enemy. I destroyed only one enemy but when I play again it destroyed all enemy.
Here's another way you could do it using PlayerPrefs then. You could save the name of the enemy as the key. That way, as long as all your enemies are named differently, it should only destroy the enemies that were destroyed last time, and not all of them. For example:
private void OnTriggerEnter(Collider other)
{
// Enemy was destroyed
Destroy(other.gameObject);
// Save this info
PlayerPrefs.SetString(other.gameObject.name, "true");
}
You'll also need a reference to all your enemies, either by referencing the parent of all the enemies, or all of them individually. I'm going to use the parent, which assumes that all enemies live under one empty gameobject called Parent:
private void Start()
{
GameObject Parent = GameObject.Find("Parent");
Transform[] enemies = Parent.GetComponentsInChildren<Transform>();
foreach (Transform enemy in enemies)
{
// if they are an enemy
if (!enemy.gameObject.CompareTag("Enemy");
continue;
string WasDestroyed = PlayerPrefs.GetString(enemy.gameObject.name);
if (WasDestroyed == "true")
Destroy(enemy.gameObject);
}
}
Answer by wolfgraphicsLLC · Jan 25, 2021 at 02:37 PM
what do you man as in another enemy spawns ? as it is impossible for the same enemy that is destroyed to just still be there it would be done in the spawn manager that is spawning the clones of a prefab in the scene and as such is where you would limit the spawning.
Your answer
Follow this Question
Related Questions
Save a game code? 1 Answer
Scene Saving In Between Runtimes 1 Answer
Reading/Writing to a text file on non-windows platforms 1 Answer
How do I save a List in my project? 0 Answers