Search Unity

Particle System Plays after Player enters Collider (3D)

Discussion in 'Physics' started by Henry_Mead, Jan 8, 2019.

  1. Henry_Mead

    Henry_Mead

    Joined:
    Dec 26, 2018
    Posts:
    4
    I've been stuck for a while on this because I can't figure out the code. I just want the particle system to be playing when the player is inside the collider then stop when the player exits. if anyone can help I'd greatly appreciate it :)
     
  2. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    96
  3. Henry_Mead

    Henry_Mead

    Joined:
    Dec 26, 2018
    Posts:
    4
    how do i use this in context?
     
  4. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    96
    the collider should be Trigger (check the property in the inspector)
    then you attach a script to it

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayParticles : MonoBehaviour
    6. {
    7.     public ParticleSystem ps;
    8.  
    9.     private void Awake()
    10.     {
    11.         ps.Stop();
    12.  
    13.     }
    14.  
    15.     private void OnTriggerEnter(Collider other)
    16.     {
    17.         ps.Play();
    18.     }
    19.  
    20.     private void OnTriggerExit(Collider other)
    21.     {
    22.         ps.Stop();
    23.     }
    24. }
    25.  
    the ParticleSystem is declared as public. So you have (after compilation) to reference it in the inspector by Dropping your ParticleSystem (if independant game object) or your Player (if yhe PS is a component of Player) in the field called ps.

    Oh! to be almost complete. If the PS is a component attached to what you call collider then you don't need to declare it public or drop anyththing... just Get it ...

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayParticles : MonoBehaviour
    4. {
    5.     ParticleSystem ps;
    6.  
    7.     private void Awake()
    8.     {
    9.         ps = GetComponent<ParticleSystem>();
    10.         ps.Stop();
    11.  
    12.     }
    13.  
    14.     private void OnTriggerEnter(Collider other)
    15.     {
    16.         ps.Play();
    17.     }
    18.  
    19.     private void OnTriggerExit(Collider other)
    20.     {
    21.         ps.Stop();
    22.     }
    23. }
    24.  
     
    Last edited: Jan 8, 2019
    Henry_Mead likes this.