【发布时间】:2016-01-07 23:32:55
【问题描述】:
我正在编写一个小程序。我有一些我希望从另一个脚本访问的小表达式。问题是当我在检查器中获得返回时(这是正确的),另一个脚本无法识别它。根据我的研究,似乎 void 不是函数的正确返回类型,我需要别的东西。
另外,由于我在检查器中得到了正确的返回,我认为值得一提的是,我在尝试在无法识别布尔值的脚本上玩游戏时收到了 Null Ref 错误
我将包含我正在使用的代码。我使用的 Unity 版本是 5.2.1f1,64 位。另外,我使用了 Awake 和 Start。两者都没有工作。因为我认为这并不重要,但我想我会试一试。
感谢您的帮助。
public class nonButtonStuff : MonoBehaviour
{
public float timer;
public float tipPercent;
public float checkAmount;
private Seated seated;
private dessert Dessert;
private drinks Drinks;
private food Food;
private appetisers Appetisers;
private checkedUpon checkedOn;
// Use this for initialization
void Awake()
{
tipPercent = .2f;
checkAmount = 0;
seated = GetComponent<Seated>();
Dessert = GetComponent<dessert>();
Drinks = GetComponent<drinks>();
Food = GetComponent<food>();
Appetisers = GetComponent<appetisers>();
checkedOn = GetComponent<checkedUpon>();
}
void Update()
{
if(seated.isSeated == true && Drinks.drinksOrdered == true || Drinks.drinksOrdered != false && seated.isSeated == false)
{
timer += Time.deltaTime * 1;
}
if(Dessert.Dessert==true)
{
timer = 0;
}
if (checkedOn.checkedOn > 0)
{
Debug.Log(checkedOn);
}
}
}
~~~~~~~~~~~~~
public class Seated : MonoBehaviour
{
public bool isSeated = false;
public void clicked()
{
isSeated = true;
Debug.Log("Was clicked.");
return;
}
}
为清楚地了解 clicked() 进行了编辑:
我使用内置的 UI 编辑器为就座添加了一个按钮。因此,没有硬编码按钮。但是,当我“播放”并单击按钮时,它给了我正确的布尔值。但是,nonButtonStuff 无法将“isSeated”识别为 == true。
【问题讨论】:
-
您遇到的问题究竟是什么。如果它是一个方法,那么该方法实现了一个接口(@987654324@ 等),然后返回值不能改变
-
确切的问题是 nonButtonStuff.cs 没有认识到在 Seated.cs 中编码的 isSeated bool 发生了变化。
-
@Tim 当我用 "seated=GetComponent
();" 调用它时,我以为我已经这样做了 -
Awake()方法何时调用?您确定当时存在Seated组件吗?您获得NullReferenceException的声明表明seated变量仅被初始化为null值,因此当然在您的Update()方法中,当您尝试访问它时会抛出NullReferenceException。 -
不幸的是,没有可靠地重现问题的a good, minimal, complete code example,或者至少没有比上述更完整的示例(很难提供完整的 Unity3d 示例),如果不是不可能的话,任何人都将很难确定问题所在。