Play Particles On Collision

Im trying to get particles to trigger on collision. Ive got a cube with box collider set to trigger. When my player collides with it I want particle effect to play. The player has rigidbody and box collider set to IsTrigger. Been working on this snippet of code however Im getting a CS0116 error ‘A namespace cannot directly contain members such as fields, methods or statements’. What am I missing? I want to put this script on the cube and have particles play when player collides with it.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public GameObject ParticlesPlay;
void OnCollisionEnter(Collision coll)
{
    if (coll.collider.CompareTag("Player"))
    {
        Play();
    }
}
       void Play()
{
    GameObject ParticlesPlay = Instantiate(ParticlesPlay, position, Quaternion.identity);
    ParticlesPlay.GetComponent<ParticleSystem>().Play();
}

It appears to me as if all that code is not inside a class.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SomeClass
{
     public GameObject ParticlesPlay;

     void OnCollisionEnter(Collision coll)
     {
         if (coll.collider.CompareTag("Player"))
         {
             Play();
         }
     }

     void Play()
     {
         GameObject ParticlesPlay = Instantiate(ParticlesPlay, position, Quaternion.identity);
         ParticlesPlay.GetComponent<ParticleSystem>().Play();
     }
}

Also, i noted you mention a trigger. Perhaps you would want to use OnTriggerEnter / Exit / Stay, opposed to collision. Just a thought. One last thing, thats not the only issue i see in the code, but, start with the easy stuff first. A proper class.

Hi. Ive changed the code to OnTriggerEnter and gave it a class but am still getting errors

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(ParticleSystem))]
public class ParticlesPlay : MonoBehaviour
{

    public ParticalSystem particaleffect;

    void Start()
    {
        particaleffect = GetComponent<ParticleSystem>();

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {

            this.GetComponent<ParticalSystem>().Play();
            Debug.Log("Played Particals!");

        }
    }
}

Actually upon examination of script its full of typos. Fixed them and now script works. Solved.