SkeletonStream NullReferenceException was unhandled
本文关键字:unhandled was NullReferenceException SkeletonStream | 更新日期: 2023-09-27 18:07:30
我正在尝试从2个Kinect传感器获取骨骼关节的X,Y,Z位置。到目前为止,我有一个简单的形式,2个按钮和6个标签。点击第一个按钮,我想在标签1、2、3中显示右手的x、y、z位置。我也想用第二个按钮,但是用第二个kinect设备。
它在一个Kinect上运行得非常好,但当我为第二个Kinect添加代码时,抛出了NullReferenceException。谁能告诉我我哪里错了?谢谢你。
编辑:观察窗口:
sensor.SkeletonStream.Enable ();的传感器。'是null
异常消息:对象引用未设置为对象的实例。
代码public partial class Form1 : Form
{
Skeleton[] skeletons;
Skeleton[] skeletons2;
public Form1()
{
InitializeComponent();
// First Kinect Device
KinectSensor sensor = KinectSensor.KinectSensors[0];
sensor.SkeletonStream.Enable(); // Here is the exception thrown
sensor.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(SensorSkeletonFrameReady);
sensor.Start();
// Second Kinect Device
KinectSensor sensor2 = KinectSensor.KinectSensors[1];
sensor2.SkeletonStream.Enable();
sensor2.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(SensorSkeletonFrameReady2);
sensor2.Start();
}
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame != null)
{
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
skeletonFrame.CopySkeletonDataTo(skeletons);
}
}
}
private void SensorSkeletonFrameReady2(object sender, SkeletonFrameReadyEventArgs e)
{
skeletons2 = new Skeleton[0];
using (SkeletonFrame skeletonFrame2 = e.OpenSkeletonFrame())
{
if (skeletonFrame2 != null)
{
skeletons2 = new Skeleton[skeletonFrame2.SkeletonArrayLength];
skeletonFrame2.CopySkeletonDataTo(skeletons2);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach(Skeleton skeleton in skeletons)
{
// get the joint
Joint rightHand = skeleton.Joints[JointType.HandRight];
// get the individual points of the right hand
double rightX = rightHand.Position.X;
double rightY = rightHand.Position.Y;
double rightZ = rightHand.Position.Z;
label1.Text = rightX.ToString();
label2.Text = rightY.ToString();
label3.Text = rightZ.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Skeleton skeleton in skeletons2)
{
// get the joint
Joint rightHand = skeleton.Joints[JointType.HandRight];
// get the individual points of the right hand
double rightX = rightHand.Position.X;
double rightY = rightHand.Position.Y;
double rightZ = rightHand.Position.Z;
label4.Text = rightX.ToString();
label5.Text = rightY.ToString();
label6.Text = rightZ.ToString();
}
}
}
这是因为您的sensor
对象为空。要修复,您应该检查您的传感器是否为空之前。这可以很容易地这样做:
KinectSensor sensor = KinectSensor.KinectSensors[0];
if (sensor != null)
{
sensor.SkeletonStream.Enable(); // Here is the exception not thrown:)
sensor.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(SensorSkeletonFrameReady);
sensor.Start();
}
开发人员工具包还提供了如何循环遍历每个可用传感器并选择第一个非空传感器的优秀示例。
在c# 6.0中,将会有一个安全的导航操作符来实现这个目的!sensor?.SkeletonStream.Enable();