Unity:GetComponent的NullReferenceException

时间:2017-06-28 20:53:10

标签: unity3d unity5 nullreferenceexception unityscript

我试图在我的Awake()函数中访问脚本类(AimRotation)来获取用户输入变量,我只得到一个NullReferenceException。我确保GameObjects不为null并且AimRotation脚本附加到对象。

令人沮丧的是,我的脚本已经完全正常工作但由于异常而突然停止工作。我不记得在代码中改变任何东西,但我不能100%肯定;我唯一可以肯定的是它发生在我用Animator(它没有访问GameObjects和AimRotation类)之后。我不确定我能提供更多信息。

编辑: 重启Unity后,NullReferenceException消失了。但是我仍然不知道是什么引起了例外。

以下是一些代码:

控制器中的唤醒功能:

protected List<RotationObject> rotObjs;

void Awake ()
{
    rotObjs = new List<RotationObject>();

    GameObject[] rotationObjects = GameObject.FindGameObjectsWithTag("Rotation");
    GameObject[] rotationObjects2 = GameObject.FindGameObjectsWithTag("Rotation2");

    for (int i = 0; i < rotationObjects.Length; i++)
    {
        AimRotation aimRot = rotationObjects[i].GetComponent<AimRotation>();
        rotObjs.Add(new RotationObject(rotationObjects[i], aimRot.getClampFactor(), aimRot.getRotationOffset()));
    }

    for (int i = 0; i < rotationObjects2.Length; i++)
    {
        AimRotation aimRot = rotationObjects[i].GetComponent<AimRotation>();
        rotObjs.Add(new RotationObject(rotationObjects2[i], aimRot.getClampFactor(), aimRot.getRotationOffset()));
    }

}

AimRotation类:

public class AimRotation : MonoBehaviour {

    public float clampFactor = 0;
    public int rotationOffset = 0;

    public float getClampFactor()
    {
        return clampFactor;
    }

    public int getRotationOffset()
    {
        return rotationOffset;
    }
}

RotationObject类:

public class RotationObject
{
    GameObject obj;
    float clampFactor;
    int rotationOffset;

    public RotationObject (GameObject newObj, float newClampFactor, int newRotationOffset)
    {
        obj = newObj;
        clampFactor = newClampFactor;
        rotationOffset = newRotationOffset;
    }

    public GameObject getGameObject()
    {
        return obj;
    }

    public float getClampFactor()
    {
        return clampFactor;
    }

    public int getRotationOffset()
    {
        return rotationOffset;
    }
}

enter image description here enter image description here

1 个答案:

答案 0 :(得分:3)

当您获得AimRotation组件

时,您的数组名称出错了
for (int i = 0; i < rotationObjects2.Length; i++)
{
    AimRotation aimRot = rotationObjects2[i].GetComponent<AimRotation>(); // was rotationObjects[i]
    rotObjs.Add(new RotationObject(rotationObjects2[i], aimRot.getClampFactor(), aimRot.getRotationOffset()));
}