My solution how to spawn hit VFX exactly where we hit the enemy.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] GameObject deathVFX;
[SerializeField] GameObject hitVFX;
[SerializeField] Transform parent;
[SerializeField] int scorePerKill = 20;
[SerializeField] int hitPoints = 20;
ScoreBoard scoreBoard;
public List<ParticleCollisionEvent> collisionEvents;
bool isAlive = true;
void Start()
{
collisionEvents = new List<ParticleCollisionEvent>();
scoreBoard = FindObjectOfType<ScoreBoard>();
}
void OnParticleCollision(GameObject other)
{
hitPoints--;
if(hitPoints>0)
{
ParticleSystem part = other.GetComponent<ParticleSystem>();
int numCollisionEvents = part.GetCollisionEvents(this.gameObject, collisionEvents);
int i = 0;
while (i < numCollisionEvents)
{
Vector3 pos = collisionEvents[i].intersection;
GameObject vfx = Instantiate(hitVFX,pos,Quaternion.identity);
vfx.transform.parent = parent;
i++;
}
}
else if(isAlive)
{
isAlive=false;
enemyKilled();
}
}
void enemyKilled()
{
scoreBoard.IncreaseScore(scorePerKill);
GameObject vfx = Instantiate(deathVFX,transform.position,Quaternion.identity);
vfx.transform.parent = parent;
Destroy(this.gameObject);
}
}