简体   繁体   中英

Starting a Particle System in Unity

(Please excuse any formatting issues) I am trying to get a simple particle system to play with an OnTriggerEnter and stop with OnTriggerExit. Following the Unity API on particle systems ( https://docs.unity3d.com/ScriptReference/ParticleSystem.Play.html ). I developed the following code:

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

public class Electric_Trap_Trigger : MonoBehaviour
{

ParticleSystem system
{
    get
    {
        if (_CachedSystem == null)
            _CachedSystem = transform.GetChild(0).gameObject.GetComponent<ParticleSystem>();
        return _CachedSystem;
    }

}

private ParticleSystem _CachedSystem;

public bool includeChildren = true;

//Start is called before the first frame update
void Start()
{
    if (system != null)
        Debug.Log("Trap found");
}

// Update is called once per frame
void Update()
{

}

private void OnTriggerEnter(Collider other)
{
    if(other.gameObject.tag == "Player")
    {
        Debug.Log("Trap Triggered by: " + other.gameObject.tag);
        if(system != null)
        {
            system.Play(includeChildren);
        }
    }
}

private void OnTriggerExit(Collider other)
{
    if (other.gameObject.tag == "Player")
    {
        Debug.Log("Trap Exited by: " + other.gameObject.tag);
        if (system != null)
        {
            system.Stop(includeChildren);
        }
    }
}

}

As you can see I have debugging code that reports the particle system has been found and the player object does indeed interact with the box collider. The particlesystem does not play. Any help would be greatly appreciated.

Answers Reviewed: playing particle system in Unity How to start and stop a particle system in Unity ? Properly play Particule System component? How to start and stop a particle system in Unity ?

As suggested:

The answer to my particular problem: "How to get an existing Unity ParticleSystem to play through script" (slightly more descriptive title). Has been solved. Please note further research is required to understand why the answer worked.

One setting in the ParticleSystem is called Prewarm. Enabling that setting allowed the system.Play and system.Stop code to start and stop the particlesystem. As previously stated, I as yet do not know why changing that setting to true (enabled) allowed the code to work.

No proper research was done. I was simply playing with settings, one at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM