【问题标题】:Null error after moving file to Standard Assets将文件移动到标准资产后出现空错误
【发布时间】:2017-03-01 08:39:14
【问题描述】:

我有工作项目,但一切都超出了标准资产。所以我需要将所有文件夹和项目移动到标准资产文件夹。当我将所有文件和文件夹移动到标准资产时,它给了我空引用错误。

我的项目中有一个命名空间,当我尝试访问这个命名空间时,它给了我 null 错误。

这是我的命名空间代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Assets.Scripts
{
  public interface IInputDetector
  {
    InputDirection? DetectInputDirection();
 }

  public enum InputDirection
 {
    Left, Right, Top, Bottom

  }
}

这里是访问它的代码

IInputDetector inputDetector = null; 

在启动方法中

void Start(){
   inputDetector = GetComponent<IInputDetector>();
 }

在更新方法中它给了我错误

var inputDirection = inputDetector.DetectInputDirection(); // Line 222

错误是这样的..

NullReferenceException:对象引用未设置为对象的实例 ControllerMovement.DetectJumpOrSwipeLeftRight () (在 Assets/Scripts/ControllerMovement.cs:222) ControllerMovement.Update () (在 Assets/Scripts/ControllerMovement.cs:106)

第 22 行在 var 行之上..

第 106 行来自我在 Update() 方法中调用的方法。

喜欢

void Update(){
  DetectJumpOrSwipeLeftRight(); // line 106
}

【问题讨论】:

  • 看起来你有一个 ControllerMovement 类型的对象,当调用 DetectJumpOrSwipeLeftRight 时它为空。然而,代码 sn-ps 不足以检查为什么会出现这种情况。您至少应该显示 detectInputs() 正在做什么,因为错误正在那里发生。
  • 哦,对不起,我打电话给 DetectJumpOrSwipeLeftRight();在更新()中。
  • ContollerMovement 是我的类名,它指向我这一行 "var inputDirection = inputDetector.DetectInputDirection(); // 第 222 行" @Nebr
  • 应该在 IInputDetector 中的 DetectInputDirection() 函数在哪里?
  • 是的,DetectInputDirection() 从命名空间返回像 "LeftSwipe", "RightSwipe" , "Top and Bottom" 这样的值,所以当用户向任何方向滑动时,我可以检查它(左 == 左)或不。 @Alox

标签: c# unity3d namespaces


【解决方案1】:

您在第 222 行中的对象 inputdetector 似乎为空。在空对象上调用DetectInputDirection() 将导致NullReferenceException

由于inputdetector一开始就设置为null,并且只通过方法Start()设置为不同的值,所以有两种可能的选择:

1.) 在到达第 222 行之前不会调用 Start(),因此 inputdetector 仍然为空。

2.) Start() 被调用,但 GetComponent&lt;IInputDetector&gt;() 产生 null。

从目前的代码sn-ps来看,还不能说到底是哪一个。

【讨论】:

  • 我认为 1) 是不可能的,因为显然 Start() 在 Update() 之前,现在我们可以专注于第二个。
  • 嗯,这对我来说并不明显,因为我看不到 Start() 何时被调用。您可以通过在行 inputDetector = GetComponent(); 处设置断点来执行此操作。并检查该方法返回的值。此外,显示 GetComponent() 实际在做什么也很有用。
  • 我不知道为什么,但我现在把标准资产和它的工作中的所有文件和文件夹都拿出来了。
  • 嗯,没关系。如果没有事先检查 inputDetector 是否为空,您仍然不应该拨打 inputDetector.DetectInputDirection() 之类的电话。总是添加类似 if(inputDetector != null) 的内容,如果它为 null 则处理这种情况(例如,返回一些错误)。
  • 是的,谢谢。我也这样做,这个小东西填充了 null getcomponent();具有价值。
猜你喜欢
  • 2021-04-26
  • 2012-03-10
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 2018-08-03
相关资源
最近更新 更多