I wrote a script to manage my Particle System emission. The starting lifespan is set to infinite so that the particle never dies until it reaches a specific collider. I didn't find any method to destroy a specific particle in the Unity Manual.
How can I do this?
Here's the code (updated to show the partial fix)
using UnityEngine;
using System.Collections.Generic;
public class PlayerDamage : MonoBehaviour
{
private ParticleSystem ps;
public List<ParticleCollisionEvent> collisionEvents;
public int attackValue = 1;
//
[Range(0.0f, 100f)]
public int maxParticles;
public float particleLife;
public bool neverDies;
public float particleSpeed = 8.0F;
void Start()
{
ps = GetComponent<ParticleSystem>();
collisionEvents = new List<ParticleCollisionEvent>();
//
var collision = ps.collision;
collision.enabled = true;
collision.type = ParticleSystemCollisionType.World;
collision.mode = ParticleSystemCollisionMode.Collision3D;
}
void OnParticleCollision(GameObject other)
{
int numCollisionEvents = ps.GetCollisionEvents(other, collisionEvents);
Rigidbody rb = other.GetComponent<Rigidbody>();
int i = 0;
while (i < numCollisionEvents)
{
if (rb.CompareTag("Enemy"))
{
BaseHealth baseHealth = other.GetComponent<BaseHealth>();
if (baseHealth != null)
{
Vector3 pos = collisionEvents[i].intersection;
Vector3 force = collisionEvents[i].velocity;// * 10;
rb.AddForce(force);
baseHealth.TakeDamage(attackValue);
}
}
i++;
}
}
void Update()
{
var collision = ps.collision;
collision.maxKillSpeed = particleSpeed;
Debug.Log("Particles Alive Count: " + GetAliveParticles());
ps.Emit(maxParticles);
var main = ps.main;
main.maxParticles = Mathf.RoundToInt(maxParticles);
main.startLifetime = particleLife;
if (neverDies)
{
particleLife = float.PositiveInfinity;
}
else
{
particleLife = 5f;
}
}
int GetAliveParticles()
{
ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount];
return ps.GetParticles(particles);
}
}
dripping water
. it starts dripping from a water source lowering the water source capacity, then it slides on the terrain and finally it reaches alake
gameObject. At this point the particle dies and raises thewater amount
int in the target. \$\endgroup\$ – bibrosko Jan 12 at 20:59void OnParticleCollision
is in conflict with the main modulevar main = ps.main;
? Maybe i should write another question to show the complete code? \$\endgroup\$ – bibrosko Jan 14 at 17:24