Unity:GetComponent 的 NullReferenceException

Unity: NullReferenceException for GetComponent

我试图在我的 Awake() 函数中访问脚本 class (AimRotation) 以获取用户输入变量,但我只收到 NullReferenceException。我确保游戏对象不为空,并且 AimRotation 脚本已附加到对象。

令人沮丧的是,我的脚本已经可以正常工作,但由于异常突然停止工作。我不记得更改了代码中的任何内容,但我不能 100% 确定;我唯一可以肯定的是它发生在我摆弄 Animator 之后(它既不访问 GameObjects 也不访问 AimRotation class)。我不确定我可以提供更多信息。

编辑: 重启 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 class:

public class AimRotation : MonoBehaviour {

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

    public float getClampFactor()
    {
        return clampFactor;
    }

    public int getRotationOffset()
    {
        return rotationOffset;
    }
}

旋转对象class:

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;
    }
}

你在获取 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()));
}