Identify Selected Prefab

I am trying to play a particle effect when an enemy is killed but it seems to play on a randomly selected one rather than the one that was hit. However the enemy that was hit still disappears and still add points to the score.

At the moment I have three scripts to carry this out (All have been shortened so I’m only showing the relevant code):

One which is attached to boxes that are thrown at enemies that detects if they have collided with an enemy prefab.

void OnCollisionEnter (Collision theCollision) {

		if (canProjectileKill == true) {
			// If the projectile hits any game object with the tag "Enemy" or "EnemyContainer".
			if (theCollision.gameObject.tag == "Enemy") {
				GameObject.Find("EnemyExplosion").GetComponent<enemyDeath>().ProjectileHasHitEnemy();
				// Destroy the projectile itself.
				Destroy (gameObject);
				// Destroy the game object that the projectile has collided with (E.g. the enemy).
				Destroy (theCollision.gameObject);
				GameObject.Find("Manager").GetComponent<projectileSpawner>().deleteProjectile();
			} 
		}
	}

Another that is attached to the enemy prefabs which detects if they have been hit by a box.

void OnCollisionEnter (Collision theCollision) {
		if(theCollision.gameObject.tag == "Projectile") {
			GameObject.Find("EnemyExplosion").GetComponent<enemyDeath>().EnemyHasBeenHit();
		}
	}

I then run an if statement asking if both the box has hit the enemy prefab AND if the enemy prefab has been hit by the box in an attempt to identify a single prefab rather than all of them. However this still doesn’t work.

	public bool HasProjectileHitEnemy;
	public bool HasEnemyBeenHitByProjectile;
	
	void Start () {
		gameObject.particleSystem.Stop();
		HasProjectileHitEnemy = false;
		HasEnemyBeenHitByProjectile = false;
	}

	public void ProjectileHasHitEnemy () {
		// From projectile.
		HasProjectileHitEnemy = true; 
	}

	public void EnemyHasBeenHit () {
		// From enemy.
		HasEnemyBeenHitByProjectile = true;
		PlayParticleSystem();
	}

	public void PlayParticleSystem () {
		if (HasEnemyBeenHitByProjectile == true && HasProjectileHitEnemy == true) {
			gameObject.particleSystem.Play();
			HasProjectileHitEnemy = false;
			HasEnemyBeenHitByProjectile = false;
		}
	}
}

I am aware this is a long question but I have been stuck on this for over a week, so any help would be much appreciated. Thank you :slight_smile:

I seem to have found a way around this. Instead I’ve just set it to instantiate the particle system whenever an enemy detects that it has collided with a projectile. I then use a Coroutine to delete the particle system 2 seconds after.