Search code examples
unity-game-engineparticlesparticle-systemcollidermesh-collider

Get Mesh of particle collider


How would I go about getting the mesh filter of a particle collision and than assign that mesh to the particle.

So I have a OnParticleCollision. I hit the object take this object I get its Mesh Filter. I than want to assign this to that of my particle so it takes the effect of its physical build.

Here is my code so far.

    void Start()
    {
        Debug.Log("Script Starting...");
        part = GetComponent<ParticleSystem>();
        collisionEvents = new List<ParticleCollisionEvent>();
    }

    void OnParticleCollision(GameObject coll)
    {
        // Getting the object of the collider
        Collider obj = coll.GetComponent<Collider>();

        Mesh mesh = obj.GetComponent<MeshFilter>().mesh;

        // Assign the mesh shape of the collider to that of the particle
        ElectricWave.shape.meshRenderer = mesh; // I know this doesnt work as is.

        // Play effect
        ElectricWave.Play();

    }

Solution

  • If you're wanting all particles in the system to take on that mesh, it's straightforward. Just get the collided-with object mesh and apply that to the ParticleSystemRenderer:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ParticleCollision : MonoBehaviour
    {
    
        private ParticleSystemRenderer particleRenderer;
    
        void Start()
        {
            particleRenderer = GetComponent<ParticleSystemRenderer>();
        }
    
        void OnParticleCollision(GameObject other)
        {
            particleRenderer.renderMode = ParticleSystemRenderMode.Mesh;
            particleRenderer.material = other.GetComponent<Renderer>().material;
        }
    }
    

    However, if you instead are looking to change the mesh of only that particle, it will be a lot more complicated, since the ParticleCollisionEvent data does not contain which particle collided with it. A good starting point might be looking at the ParticleCollisionEvent.intersection value, and trying to find the particle nearest that point using GetParticles. It might be extrememly computationally expensive, though, if it works at all.

    An easier way might be to fake it by having multiple particle systems with extremely low emission rates, so that changing the mesh of a whole particle system results in changing just one visible particle, and resetting the system's mesh before every new particle is emitted. That way you get the visual effect you're looking for, but under the hood it's multiple particle systems acting as one.