- Home /
Question by
Vitka · Feb 13, 2015 at 07:27 PM ·
c#collisioninstantiateprefab
Issues with instantiated prefabs
I'm new to unity and C#. Last week I started to read a tutorial and I have some troubles with a shoot'em up prototype.
I want to instantiate a prefab (PowerUp) after destroying a enemy. Now it's possible for multiple Projectiles to hit an Enemy on the same turn that the Enemy’s health drops to 0. This will cause multiple PowerUps to be spawned.
Know I have to change the code to stop this from happening. The goal is to drop only one PowerUp per enemy. And I have no idea how to achive this.
Your help is highly appreciated.
public class Enemy : MonoBehaviour {
public int showDamageForFrames = 2; // # frames to show damage
public float powerUpDropChance = 1f; // Chance to drop a power-up
public bool ________________;
...
void OnCollisionEnter( Collision coll ) {
...
case "ProjectileHero":
...
if (health <= 0) {
// Tell the Main singleton that this ship has been destroyed
Main.S.ShipDestroyed( this );
// Destroy this Enemy
Destroy(this.gameObject);
public class Main : MonoBehaviour {
...
public WeaponDefinition[] weaponDefinitions;
public GameObject prefabPowerUp;
public WeaponType[] powerUpFrequency = new WeaponType[] {
WeaponType.blaster, WeaponType.blaster,
WeaponType.spread,
WeaponType.shield };
public bool ________________;
...
public void ShipDestroyed( Enemy e ) {
// Potentially generate a PowerUp
if (Random.value <= e.powerUpDropChance) {
// Random.value generates a value between 0 & 1 (though never == 1)
// If the e.powerUpDropChance is 0.50f, a PowerUp will be generated
// 50% of the time. For testing, it's now set to 1f.
// Choose which PowerUp to pick
// Pick one from the possibilities in powerUpFrequency
int ndx = Random.Range(0,powerUpFrequency.Length);
WeaponType puType = powerUpFrequency[ndx];
// Spawn a PowerUp
GameObject go = Instantiate( prefabPowerUp ) as GameObject;
PowerUp pu = go.GetComponent<PowerUp>();
// Set it to the proper WeaponType
pu.SetType( puType );
// Set it to the position of the destroyed ship
pu.transform.position = e.transform.position;
}
}
Comment
Answer by hexagonius · Feb 13, 2015 at 09:49 PM
Use a boolean (spawnedPickup). Set it to true when you do so and check if you should spawn based on it.