Search code examples
c#unity-game-engineparticlesparticle-system

How to play particles for a specific cloned game object in Unity?


I am now making a simple game in Unity. There are cones falling from the sky and player needs to control a cube to dodge them. When a cone hit the cube, it decreases the cube's HP and emit some particles. Here is my script :

public class move : MonoBehaviour{

ParticleSystem particle;

static move instance;

void Start()
{
    particle = FindObjectOfType<ParticleSystem>();
    instance = this;
}

public static void PlayParticles()
{
    instance.particle.Play();
}
}

Second:

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("cone"))
    {
        move.PlayParticles();
        GameDirector.DecreaseHp(0.25f);

    }

}

The first script is attached to the cone prefab and the second one is attached to the cube. But the problem is that when a cone hit the cube, other cones emit particles instead of the cone that hit the cube. How can I solve the problem? Any help is greatly appreciated!


Solution

    1. Remove cone-related logic from cube:

      private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("cone")) { // move.PlayParticles(); //------------ remove this line GameDirector.DecreaseHp(0.25f); }

      }

    2. Make particle variable assignable in inspector - add [SerializeField] attribute. And assign it in inspector.

    3. Add collision processing into your cone script.
    4. Remove unnecessary statics from script.

    Something like this:

    public class move : MonoBehaviour
    {
    
    [SerializeField] //------- Add attribute and do not forget to assign PS in inspector
    ParticleSystem particle;
    
    //static move instance; //----- Remove
    
    //Remove Start:
    /*
        void Start()
        {
            particle = FindObjectOfType<ParticleSystem>();
            instance = this;
        }
    */
    //Remove PlayParticles:
    /*
        public void PlayParticles()
        {
            Change:
            instance.particle.Play();
        }
    */
        //---- Add collision check
        private void OnCollisionEnter(Collision collision)
        {
            if (collision.gameObject.CompareTag("cube")) //----- Set proper tag to your cube
            {
                particle.Play();
            }
    
        }
    
    }