Items are remaining after ending play with OnDisable,When OnDisable is triggered, objects sometimes remain after game is ended
Hi, creating a 2D Platformer with enemies you can destroy and they'll drop powerups. I have a 50% drop for an health up, and a 50% for a mana up. That's working fine. However, if I haven't killed the enemy and claimed its power up by the time I end the game, a copy of a mana up appears right where they had been standing at the game's end. I thought this was a problem with OnDestroy, but maybe it's both? I tried putting the relevant code right before the enemy was destroyed, but that did nothing.
Here's the current code:
void OnDisable() {
randDrop = Random.Range (1, 10);
if (randDrop <= 5) {
Instantiate (hpUp, dropPoint.position, dropPoint.rotation);
} else {
Instantiate (mpUp, dropPoint.position, dropPoint.rotation);
}
}
Here was the old thing that I tried and didn't work, causing me to switch to OnDisable:
public void ChangeEnemyHealth (int health) {
totalHealth += health;
if (totalHealth <= 0) {
randDrop = Random.Range (1, 10);
if (randDrop <= 5) {
Instantiate (hpUp, dropPoint.position, dropPoint.rotation);
} else {
Instantiate (mpUp, dropPoint.position, dropPoint.rotation);
}
GameObject.Find("UI").GetComponent<UIControl>().changeScore (score);
Destroy (gameObject);
}
}
Comment
Best Answer
Answer by TBruce · Dec 09, 2016 at 07:28 PM
This will work for you (tested)
public GameObject hpUp;
public GameObject mpUp;
public Transform dropPoint;
bool gameInPlay = true;
void OnApplicationQuit()
{
gameInPlay = false;
}
void OnDisable()
{
if (gameInPlay)
{
int randDrop = Random.Range (1, 10);
if ((randDrop <= 5) && (hpUp != null))
{
Instantiate (hpUp, dropPoint.position, dropPoint.rotation);
}
else if (mpUp != null)
{
Instantiate (mpUp, dropPoint.position, dropPoint.rotation);
}
}
}