Search Unity

How to turn on and off a particle emmission via script

Discussion in 'General Graphics' started by BrewNCode, Mar 20, 2018.

  1. BrewNCode

    BrewNCode

    Joined:
    Feb 17, 2017
    Posts:
    372
    Hello, I have a problem here. I have a script for some sparks with the particle system. I want to make the sparks look like they appear and disappear (the catch here is that the sparks come from an engine that is damaged). How can I turn the emission on and off randomly? I was thinking of making a boolean with a float Random.Range of 1 to 2 seconds.


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

    public class SparksEditor : MonoBehaviour {


    public Mesh myMesh;
    void Start() {
    ParticleSystem ps = GetComponent<ParticleSystem>();
    var main = ps.main;
    var em = ps.emission; em.enabled = true;
    var sh = ps.shape; sh.enabled = true;


    // Emiter
    main.duration = 2.0f;
    main.loop = true;
    main.startLifetime = 0.5f;
    main.startSpeed = 5.0f;
    main.startSize = 0.01f;
    main.gravityModifier = 0.5f;

    // Emission
    em.rateOverTime = 50.0f;
    em.rateOverDistance = 0.0f;

    // Shape
    sh.shapeType = ParticleSystemShapeType.Cone;
    sh.angle = 15.0f;
    sh.radius = 0.01f;
    }
    }



    That is my script ^
     
  2. Koyemsi

    Koyemsi

    Joined:
    Sep 25, 2017
    Posts:
    29
    Hi, to turn on or off the emission, just use ps.Play() or ps.Stop()
    Maybe something like that would do the job :
    Code (CSharp):
    1. public class sparks : MonoBehaviour {
    2.     private ParticleSystem ps;
    3.  
    4.     void Start () {
    5.         ps = GetComponent<ParticleSystem> ();
    6.         StartCoroutine ("StartOrStopEmission");
    7.     }
    8.      
    9.     IEnumerator StartOrStopEmission () {
    10.         if (ps.isPlaying)
    11.             ps.Stop ();
    12.          else
    13.             ps.Play ();
    14.  
    15.         float timeToWait = Random.Range (1f, 2f);
    16.         yield return new WaitForSeconds (timeToWait);
    17.  
    18.         StartCoroutine ("StartOrStopEmission");
    19.     }
    20. }
     
    BrewNCode likes this.
  3. BrewNCode

    BrewNCode

    Joined:
    Feb 17, 2017
    Posts:
    372
    Thank you very much for the help
     
  4. Koyemsi

    Koyemsi

    Joined:
    Sep 25, 2017
    Posts:
    29
    You're welcome, hope this will help.
    By the way, you're the first I've ever helped about Unity, as I usually ask for help myself ;)
     
    BrewNCode and richardkettlewell like this.
  5. BrewNCode

    BrewNCode

    Joined:
    Feb 17, 2017
    Posts:
    372
    Good to know that you actually are now hel[ing :D. The tables have turned : D
     
    Koyemsi likes this.