停用其他游戏对象的脚本

时间:2021-01-27 10:47:40

标签: c# unity3d

我正在为多个游戏对象使用一个脚本。如果我当前的游戏对象被触发,我希望脚本在除当前游戏对象之外的所有其他游戏对象上停用。我可以在禁用当前脚本后将其设置为活动状态。但我根本不希望它被启用为 false。我如何实现这一目标?

public MyScript[] myScript;

void Start () {
        myScript= FindObjectsOfType (typeof (MyScript)) as MyScript[];
    }

void Activated() {
        for (int i = 0; i < myScript.Length; i++) {
            myScript[i].enabled = false; //All other scripts except for current gameObject's script
        }

1 个答案:

答案 0 :(得分:0)

  1. 事件系统

类似的东西。

public class MyScript : MonoBehaviour
{
    public static event Action<GameObject> Triggered;

    private void Start()
    {
        MyScript.Triggered += OnTriggered;
    }

    private void OnTriggered(GameObject triggeredGameObject)
    {
        if (triggeredGameObject != gameObject)
        {
            enabled = false;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        Triggered?.Invoke(gameObject);
    }
}
  1. 你的方式

您需要以某种方式将触发的游戏对象传递给 Activated 函数,以便进行比较

    public MyScript[] myScript;
    
    void Start () {
            myScript= FindObjectsOfType (typeof (MyScript)) as MyScript[];
        }
    
    void Activated(GameObject triggeredGameObject)// pass the triggered gameobject here
 {
            for (int i = 0; i < myScript.Length; i++) 
{
           if(triggeredGameObject != myScript[i].gameObject)
                myScript[i].enabled = false;
            }