Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在多个脚本中使用相同的布尔值_C#_Unity3d - Fatal编程技术网

C# 在多个脚本中使用相同的布尔值

C# 在多个脚本中使用相同的布尔值,c#,unity3d,C#,Unity3d,我试图让玩家在找到钥匙后打开门 如果玩家的密钥为true或false,“hasKey”值当前处于管理状态。我现在需要知道如何在另一个脚本中使用这个“hasKey”布尔值;我已经尝试了好几个小时,但没有结果,所以我将在下面发布我的代码,也许有人知道发生了什么,提前谢谢 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems;

我试图让玩家在找到钥匙后打开门 如果玩家的密钥为true或false,“hasKey”值当前处于管理状态。我现在需要知道如何在另一个脚本中使用这个“hasKey”布尔值;我已经尝试了好几个小时,但没有结果,所以我将在下面发布我的代码,也许有人知道发生了什么,提前谢谢

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

public class Detection : MonoBehaviour {

    public GameObject objectToEnable;
    public static bool Enabled = false;
    public bool hasKey = false;
    public DoorOpener _DoorOpener;


    private void Update()
    {
        Debug.Log(hasKey);
        if (Enabled)
        {
            objectToEnable.SetActive(true);
        }
    }



    void OnMouseEnter()
    {

        Debug.Log("Enter");
    }

     void OnMouseExit()
    {
        Debug.Log("Exit");
    }

     void OnMouseUp()
    {
        Enabled = true;
        hasKey = true;
        Debug.Log("Pressed");
    }

}





public class DoorOpener : MonoBehaviour
{

    Animator animator;
    bool JailDoorOpen;


    public Detection _Detection;

    void Start()
{

    JailDoorOpen = false;
    animator = GetComponent<Animator>();
 }



    void OnTriggerEnter(Collider JailDoorO)
    {
        if ((JailDoorO.gameObject.tag == "Player") && (_Detection.hasKey == true))
        {
            Debug.Log("Open Door");
            JailDoorOpen = true;
            jDoors("Open");
        }

    }


    void jDoors (string direction)
    {
        animator.SetTrigger(direction);

        }

}

    enter code here

如果这是一个本地多人游戏,您可以将布尔值存储在门对象上。您还可以将其存储在KeyManager中,并通过静态变量访问它


如果这是一个网络多人游戏,您必须将变量存储在某个管理器中,并在布尔值状态发生变化时更新每个客户端。

在第二个脚本中,您声明:

public Detection _Detection;
但是你还没有说什么是被分配的。所以它只是检测脚本的一个空白实例。您需要引用附加到正在查找的特定对象的脚本。 例如,如果Detection和DoorOpener都在同一个游戏对象上,您可以这样做

_检测=gameObject.getComponent

或者你可以做一些像

_Detection = GameObject.FindWithTag('TagOfObjWithDetScript').getComponent<Detection>();

现在,DoorOpener中的haskey值与您正在使用的检测脚本的特定实例中的haskey值相匹配。

这两个脚本位于不同的对象上;检测脚本在父脚本上,开门器在JailDoor上,我只需要JailDoor注册“hasKey”为true,这样我就可以在if语句中使用它来打开doorOk,同样的过程也适用。只需在任何需要其值的对象中引用父对象上检测脚本的确切实例。