【发布时间】:2019-07-29 14:37:39
【问题描述】:
(请原谅任何格式问题) 我正在尝试获得一个简单的粒子系统来使用 OnTriggerEnter 并使用 OnTriggerExit 停止。遵循粒子系统上的 Unity API (https://docs.unity3d.com/ScriptReference/ParticleSystem.Play.html)。我开发了以下代码:
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);
}
}
}
}
如您所见,我有调试代码报告粒子系统已找到并且玩家对象确实与盒子碰撞器交互。粒子系统不播放。任何帮助将不胜感激。
已审核答案: 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 ?
【问题讨论】:
-
您是否进行了检查以确保您确实拥有粒子系统?在
if(system != null)中添加调试语句。 -
另外,你的代码很容易出错,如果你改变了“玩家”标签,这段代码将永远不会运行,更不用说如果关联的对象在索引 0 处没有子对象,你会得到一个空引用错误。最好在docs.unity3d.com/ScriptReference/… 上查看函数
GetComponentInChildren文档,或者至少在调用它的游戏对象之前添加一个检查以查看您是否在索引0 处有一个孩子。 -
来自您的链接:以下示例创建一个用于操作粒子系统的 GUI 窗口。那是你真正需要的吗?操纵该粒子系统的 GUI?或者您只需要以编程方式启动和停止粒子系统?
-
@IgnacioAlorre 不管它是一种创建 GUI 窗口的方法,播放命令的功能都是相同的,即播放粒子系统。他的其他链接不仅仅指向与 GUI 相关的文章。
-
@Eddge 根据我的 Start 方法中的调试代码,系统确实存在。此外,ParticleSystem 是 GameObject 的子对象,其 BoxCollider 设置为 IsTrigger。它们都作为活动对象存在于场景空间中。最后 - 我刚刚解决了这个问题,我将其标记为已解决。显然,我需要将 ParticleSystem 设置为 Prewarm。将该选项更改为 true 可使系统按脚本运行。我不知道为什么,这当然需要研究。谢谢大家的回答。