- Home /
Item Drops on enemy spawn and death?
so I have a health potion to drop on the enemy death when it basically collides with my other objects and the giving it a random chance 25% at the moment to drop the item (potion). but currently it is dropping on both spawn and destroy. some help would be amazing :D
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DestroyAI : MonoBehaviour { public GameObject Healthpot; public float dropRate = 0.25f; //25% drop chance public Transform HealthPotSpawn;
void OnCollisionEnter (Collision col)
{
if (col.transform.tag == "Bullet")
Destroy (gameObject);
else if (col.transform.tag == "Player")
Destroy (gameObject);
else if (col.transform.tag == "Enemy")
Destroy (gameObject);
else if (col.transform.tag == "Gooba")
Destroy (gameObject);
if (Random.Range (0f, 1f) <= dropRate)
Instantiate (Healthpot, HealthPotSpawn.position, HealthPotSpawn.rotation);
}
}
I think enemy must be hitting something other than Bullet,Player,Enemy,Gooba when it spawns. Could check what it hits with:
Debug.Log(col.gameObject.name);
If my assumptions are right, you could move your Instantiate inside the if statements.
Answer by calebheale · Oct 04, 2017 at 07:36 AM
You need curly braces around the last "else if" response.
void OnCollisionEnter (Collision col)
{
if (col.transform.tag == "Bullet")
Destroy (gameObject);
else if (col.transform.tag == "Player")
Destroy (gameObject);
else if (col.transform.tag == "Enemy")
Destroy (gameObject);
else if (col.transform.tag == "Gooba") { // add open curly
Destroy (gameObject);
if (Random.Range (0f, 1f) <= dropRate)
Instantiate (Healthpot, HealthPotSpawn.position, HealthPotSpawn.rotation);
} // add close curly
} // fix your indenting for clarification
I would also recommend using that syntax for all "if" and "else if" statements as it helps code readability. And I would also recommend reading this article for further clarification: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/if-else
Your answer
![](https://koobas.hobune.stream/wayback/20220612140230im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
BoxCollider2D failling verification when Instantiate (Fixed, Cause: big derp) 1 Answer
Instantiate Prefabs on sphere surface(mini planet) 1 Answer
Collision Damage, Hit points and Instantiate 1 Answer
[SOLVED] Destroy instantiated object prefab on collision 1 Answer
Instantiating random prefabs when the player passes through a trigger 1 Answer