【问题标题】:NullReferenceException @ OnGUINullReferenceException @ OnGUI
【发布时间】:2015-01-12 00:49:13
【问题描述】:

我了解以下错误消息是在(通常)Unity 告诉我 myProg 脚本第 54 行中的某件事不存在时引起的:

NullReferenceException: Object reference not set to an instance of an object
myProg.OnGUI () (at Assets/Scripts/Editors/myProg.cs:54)

但就我所见所想,那里没有任何遗漏......

这里是代码sn-p的相关部分,第54行是.enabled的位(中间行):

if( GUILayout.Button("SART07Johnson") )
    {
        stage.setFatigueInductor( new Sart07JohnsonDefinition(GetComponent<ExperimentCreator>().getExperiment().getAvailableTableName("SART07Johnson")) );
        stage.setTypeOfFI( FatigueType.SART07Johnson );
        SART07JohnsonEditor editorSart07Johnson = GetComponent<SART07JohnsonEditor>();
        editorSart07Johnson.enabled = true;
        editorSart07Johnson.Init( (Sart07JohnsonDefinition)stage.getFatigueInductor(), this.stage.StageName,GetComponent<ExperimentCreator>().getExperiment().GetExperimentName() );
        GetComponent<NavigationTree>().CurrentEditor = editorSart07Johnson;
        this.enabled = false;
    }

所以,我想知道...还有什么问题?我可以调查的任何其他可能导致生成此错误消息的具体原因?

【问题讨论】:

  • 一般来说,错误信息不会“撒谎”,我建议您发布所涉及的实际代码,以便人们可以验证它不是导致问题的代码。
  • 你需要给我们看第 54 行,伙计。
  • 谢谢大家。我添加了那条特定的行,但我没有这样做的原因是因为它需要我发布 GetComponent 引用的其他程序......
  • 这个脚本附加的GameObject包含一个“SART07JohnsonEditor”组件?
  • 是的,GetComponent 引用了一个名为 SART07JohnsonEditor 的现有 C# 脚本

标签: unity3d nullreferenceexception


【解决方案1】:

你是对的,它告诉你一个对象不存在。在这种情况下,editorSart07Johnson 为 null,您正试图从中获取属性 (.enabled)。上面的行调用GetComponent,根据文档“如果游戏对象附加了一个,则返回 Type 类型的组件,如果没有,则返回 null。”

所以答案是您的游戏对象没有附加SART07JohnsonEditor 类型的组件。

【讨论】:

  • 但是 GetComponent 调用 SART07JohnsonEditor 这意味着我的游戏对象现在附加了 SART07JohnsonEditor?不对吗?
  • GetComponent 不会附加组件,它只会返回对已附加组件的引用。首先使用AddComponent 附加一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多