在FixedUpdate() 中的第一个脚本中,我调用此函数:
private void FixedUpdate()
{
RotateView();
}
旋转 View 内部:
public void RotateView()
{
gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);
}
在第二个脚本中,我像这样调用 RotateView :
Whilefun.FPEKit.FPEPlayer.Instance.GetComponent<Whilefun.FPEKit.FPEFirstPersonController>().RotateView();
但现在我想使用 RotateView 函数向脚本添加一个 bool 值,这样我就可以在第二个脚本中决定是否在 FixUpdate 中调用 RotateView。
我想控制是否在第二个脚本的FixedUpdate中调用RotateView,或者更好地控制是否行:
gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);
是否执行取决于我在第二个脚本中设置的标志,例如:
Whilefun.FPEKit.FPEPlayer.Instance.GetComponent<Whilefun.FPEKit.FPEFirstPersonController>().RotateView(false);
false 所以它不会使用该行:
gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);
true 会使用它。如果要从第一个脚本中的 FixUpdate 内部调用 RotateView,则为 false/true。
最佳答案
有很多方法可以做到这一点:
- 您可以使用
[SerializeField] OtherScript foo;
通过检查器将一个脚本分配给另一个脚本 - 您可以将 bool 值公开并
static
,然后可以通过OtherScript.foo
访问它 - 您可以使用多种方法之一来获取
Start()
中的其他组件。其中一个脚本的,例如FindObjectByType()
或GetComponent<...>()
或GetComponentInChildren<...>()
,然后 bool 可以是 public 或 public 但使用 { get;私有(private)套装; } 访问器,或者通过像GetFoo()
这样的公共(public)函数提供 - 对于 super 罕见的 bool 检查,例如初始加载设置,还有
PlayerPrefs
Unity 中的类(但通常会被放入另一个变量中) - 您甚至可能会发现您使用共享 bool 方法是错误的,而是希望让一个类处理
RotateView
对方的电话等。
这在某种程度上取决于您如何构建程序、类应该做什么、它们的范围是什么等等。
关于c# - 如何在两个脚本中使用 bool 来决定是否调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60021433/