计算链中骨骼信息时"NullReferenceException: Object reference not set to an instance of an object"错误



所以,我一直在尝试进行反向运动学,在进行反向运动学的同时,我想出了这个代码来获取链中单个骨骼的变换和长度的信息。它计算所需的数据并将其放入一个表"0"中;BoneSpecialStruct";结构;BoneChain";。然后它应该写下";BoneChain";在调试控制台中。

实际IK为WIP。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InverseKinematics : MonoBehaviour
{
BoneSpecialStruct HighestParent;
BoneSpecialStruct[] BoneChain;
public int TargetChainLength;
public Transform IKtarget;
public struct BoneSpecialStruct
{
public Transform transform;
public float length;
public BoneSpecialStruct(Transform transform, float length)
{
this.transform = transform;
this.length = length;
}
}
void Start()
{
HighestParent.transform = transform;
Vector3 TempLength = new Vector3();
TempLength.x = HighestParent.transform.parent.position.x - HighestParent.transform.position.x;
TempLength.y = HighestParent.transform.parent.position.y - HighestParent.transform.position.y;
TempLength.z = HighestParent.transform.parent.position.z - HighestParent.transform.position.z;
HighestParent.length = Mathf.Pow(TempLength.y, 2) + (Mathf.Pow(TempLength.x, 2) + Mathf.Pow(TempLength.z, 2));
BoneChain[0] = new BoneSpecialStruct(HighestParent.transform, HighestParent.length);
for (int i = 0; i < TargetChainLength; i++)
{
HighestParent.transform = HighestParent.transform.parent;
TempLength.x = HighestParent.transform.parent.position.x - HighestParent.transform.position.x;
TempLength.y = HighestParent.transform.parent.position.y - HighestParent.transform.position.y;
TempLength.z = HighestParent.transform.parent.position.z - HighestParent.transform.position.z;
HighestParent.length = Mathf.Pow(TempLength.y, 2) + (Mathf.Pow(TempLength.x, 2) + Mathf.Pow(TempLength.z, 2));
BoneChain[i] = new BoneSpecialStruct(HighestParent.transform, HighestParent.length);
}
foreach (BoneSpecialStruct Bone in BoneChain)
{
Debug.Log(Bone);
}
}
void FixedUpdate()
{
//WIP
}
}

应获取链中骨骼的信息然而,当它运行时,我得到错误

NullReferenceException: Object reference not set to an instance of an object
InverseKinematics.Start () (at Assets/InverseKinematics.cs:32)

不知道怎么修。救命。

我使用的是unity 2020.4f1个人版,带有Visual Studio代码和.NET 5.0

看起来您试图在不初始化数组(BoneChain(的情况下使用它。因此,当您尝试使用BoneChain[0] = ...分配给它的第一个元素时,您会得到一个NullReferenceException

在分配给数组元素之前,您需要初始化数组,使用类似的方法

BoneChain = new BoneSpecialStruct[TargetChainLength];

在CCD_ 4方法开始时。

或者,您可以使用(例如(List<BoneSpecialStruct>,依次添加元素,然后在foreach循环之前的末尾调用.ToArray()

相关内容

最新更新