正如我所见,您(ab!)对所有事情都使用单例模式,并调用了很多东西 static,而应该是实例化的方法/属性。
所以假设每个预制件都有你的 move 脚本和 ParticleSystem 在它自己的层次结构中的某个地方,你宁愿这样做
public class move : MonoBehaviour
{
// Already reference this via the Inspector by dragging the
// GameObject with the ParticleSystem into this slot
[SerializeField] private ParticleSystem particle;
private void Awake()
{
// As fallback get it on runtime
if(!particle) particle = GetComponentInChildren<ParticleSystem>(true);
}
// Use a normal instanced method
public void PlayParticles()
{
particle.Play();
}
}
然后从碰撞中获取实例:
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("cone"))
{
// Get the instance of the component
var moveInstance = collision.gameObject.GetComponent<move>();
if(!moveInstance)
{
Debug.LogError($"There is no {nameof(move)} component attached to the colliding object {collision.gameObject.name}!", this);
}
else
{
// call the method of this instance
moveInstance.PlayParticles();
}
GameDirector.DecreaseHp(0.25f);
}
}
但您似乎也可以让您的播放器自己直接处理整个事情。而是将粒子系统附加到它上面并将move 放在播放器(立方体)上,就像
public class move : MonoBehaviour
{
// Already reference this via the Inspector by dragging the
// GameObject with the ParticleSystem into this slot
[SerializeField] private ParticleSystem particle;
void Start()
{
if(!particle) particle = GetComponentInChildren<ParticleSystem>(true);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("cone"))
{
particle.Play();
GameDirector.DecreaseHp(0.25f);
}
}
}
注意:GameDirector 可能是一样的,你应该有一个字段
[SerilaizeField] private GameDirector gameDirector;
并且要么通过检查器引用它,要么(仅作为后备)在运行时通过
获取它
private void Awake()
{
if(!gameDirector) gameDirector = FindObjectOfType<GameDirector>();
}
这里FindObjectOfType 似乎“没问题”,因为GameDirector 听起来像是场景中只存在一次的东西。