简体   繁体   English

从 C# 中的不同类访问布尔值

[英]Accessing boolean from a different class in C#

I have one collision script in which I set a boolean to true or false我有一个碰撞脚本,其中我将布尔值设置为 true 或 false

using UnityEngine;
using System.Collections;

public class IsTriggerLockCamera : MonoBehaviour {
    public bool CameraLock = false;

    public void OnTriggerStay2D(Collider2D other) {
        CameraLock = true;
        Debug.Log ("Im inside"); 

    }

        public void OnTriggerExit2D(Collider2D other) {
        CameraLock = false;
        Debug.Log ("I exited");
    }


}

I want to access this boolean from my camera script, I tried this我想从我的相机脚本访问这个布尔值,我试过这个

if (CameraLock == true) {
            Debug.Log ("Im locked");
        }

However, I get an error saying that CameraLock doesn't exist in the current context.但是,我收到一条错误消息,指出当前上下文中不存在 CameraLock。 The boolean is public so I'm very confused.布尔值是公开的,所以我很困惑。


EDIT: I feel like I didn't give good enough info so I'll start by posting the whole camera script and then clarifying.编辑:我觉得我没有提供足够好的信息,所以我将首先发布整个相机脚本,然后进行澄清。

using System;
using UnityEngine;

    public class CameraFollowLockY : MonoBehaviour
    {
        public Transform target;
        public float damping = 1;
        public float lookAheadFactor = 3;
        public float lookAheadReturnSpeed = 0.5f;
        public float lookAheadMoveThreshold = 0.1f;

        private float m_OffsetZ;
        private Vector3 m_LastTargetPosition;
        private Vector3 m_CurrentVelocity;
        private Vector3 m_LookAheadPos;

        private void Start()
        {
            m_LastTargetPosition = target.position;
            m_OffsetZ = (transform.position - target.position).z;
            transform.parent = null;
        }


        private void Update()
        {
            float xMoveDelta = (target.position - m_LastTargetPosition).x;

            bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;

            if (updateLookAheadTarget)
            {
                m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
            }
            else
            {
                m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
            }

            Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
            Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);

            transform.position = newPos;
            transform.position = new Vector3(transform.position.x, 0, transform.position.z);

            m_LastTargetPosition = target.position;


        if (CameraLock == true) {
            Debug.Log ("Im locked");
        }
}

The IsTriggerLockCamera is a script I used for an invisible collider in Unity. IsTriggerLockCamera是我在 Unity 中用于隐形碰撞器的脚本。 My camera is focused on the player at all times, but I want it to stop moving when the player is close to reaching the edge of the map, so he can notice that the map is ending.我的相机始终聚焦在玩家身上,但我希望它在玩家接近地图边缘时停止移动,以便他可以注意到地图即将结束。 The original plan was, that the collider would send out information when player enters it and then instead of Debug.Log ("Im Locked");最初的计划是,碰撞器会在玩家进入时发送信息,然后而不是Debug.Log ("Im Locked"); would be some code that would lock the camera in place.将是一些将相机锁定到位的代码。 I don't know if this solution is very elegant and I'd like to apologize for not clarifying everything properly beforehand, but I started coding probably 2 months ago (I did only Rails websites) and I got into C# game development about a week ago so I'm still missing the terminology required to properly describe the problems I encounter.我不知道这个解决方案是否非常优雅,我想为没有事先正确澄清所有内容而道歉,但我大约在 2 个月前开始编码(我只做 Rails 网站)并且我大约一个星期进入了 C# 游戏开发以前,所以我仍然缺少正确描述我遇到的问题所需的术语。 So far, no suggestion has worked.到目前为止,没有任何建议奏效。 The closest working suggestion was OnoSendai's suggestion, but apparently it's not allowed to create MonoBehaviour using "new".最接近的工作建议是 OnoSendai 的建议,但显然不允许使用“new”创建 MonoBehaviour。


Edit2: Making the boolean static didn't work at first, but then I realized that I had to make some changes in my camera script as well, so it works now, but Philip said that it's a bad advice - I personally have no idea why, I assume that it's something like using !important in CSS, you just use it as a last resort because it makes the code not that flexible - so I'm still open to ideas. Edit2:首先使布尔静态不起作用,但后来我意识到我也必须对我的相机脚本进行一些更改,所以现在可以使用了,但菲利普说这是一个糟糕的建议 - 我个人不知道为什么,我认为它就像在 CSS 中使用 !important 一样,你只是将它用作最后的手段,因为它使代码不那么灵活 - 所以我仍然对想法持开放态度。

You may want to try a full reference to the CameraLock property based on the object instance - as in 您可能想尝试基于对象实例对CameraLock属性的完整引用-如

    var objRef = new IsTriggerLockCamera(); // Just an example of object reference - 
                                            // You may already have one
                                            // on your code.

    if (objRef.CameraLock) {
        Debug.Log ("Im locked");
    }

That happens because CameraLock is marked as public , but not as static - it only exists on a instantiated object. 发生这种情况是因为CameraLock被标记为public ,而不是static -它仅存在于实例化对象上。

If your camera needs access to the IsTriggerLockCamera then dependency injection is good way to make it clear : 如果您的相机需要访问IsTriggerLockCamera,则依赖项注入是明确说明的好方法:

class Camera{
    private readonly IsTriggerLockCamera _locker;
    public Camera(IsTriggerLockCamera locker){
       if (locker== null)
       {
           throw new ArgumentNullException("locker");
       }
       _locker = locker;
    }
    public void whatevermethod(){
        if (_locker.CameraLock){
           ...
        } 
    }
}

You need to set the variable you want to access from other scripts, static as well as public. 您需要设置要从其他脚本(静态和公共脚本)访问的变量。

using UnityEngine;
using System.Collections;

public class IsTriggerLockCamera : MonoBehaviour {
public static bool CameraLock = false;

public void OnTriggerStay2D(Collider2D other) {
    CameraLock = true;
    Debug.Log ("Im inside"); 

}

    public void OnTriggerExit2D(Collider2D other) {
    CameraLock = false;
    Debug.Log ("I exited");
}

} }

Then you can access CameraLock : 然后,您可以访问CameraLock

if (CameraLock == true) {
        Debug.Log ("Im locked");
    }

I would like to suggest some approach, 我想提出一些方法,

  1. Make CameraLock variable as protected. 将CameraLock变量设为受保护。
  2. Create a new class and make IsTriggerLockCamera class as base class. 创建一个新类,并将IsTriggerLockCamera类作为基类。
  3. consume the CameraLock variable and work on it. 使用CameraLock变量并对其进行处理。

Thanks, 谢谢,

you could make a function that sets the bool then a function that returns it then you could put that in the file with the bool then call those functions from the other file您可以创建一个设置 bool 的函数,然后创建一个返回它的函数,然后您可以将它放在带有 bool 的文件中,然后从另一个文件中调用这些函数

bool Saved
public void SetSaved(bool issaved)
{
    Saved = issaved;
}

public bool GetSaved()
{
    return Saved;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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