C#对象引用未设置为Object的实例 [英] C# Object reference not set to an instance of an Object

查看:140
本文介绍了C#对象引用未设置为Object的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!



这里我的代码:



Hello !

Here my code :

using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using UnityEngine;
using System;


public class Recup_donnees_6bis : MonoBehaviour {

	private class Data_struct {

		public String marker_name ; 
		public Vector3 [] positions ; 


	}
		private static Data_struct [] nv_data ;

		static GameObject [] body ; 
		string[][] datas; 

		int cpt = 0 ; 


	// When the script instance is being loaded

	void Awake ()

	{
		Application.targetFrameRate = 25; 
	}


	// Use this for initialization

	void Start() 

	{
		body = new GameObject[55]; 

		body [0] = GameObject.Find ("RightUpLeg"); 
		body [1] = GameObject.Find ("LeftUpLed");
		body [5] = GameObject.Find ("Neck");
		body [6] = GameObject.Find ("RightArm");
		body [7] = GameObject.Find ("LeftArm");
		body [8] = GameObject.Find ("Throat");
		body [9] = GameObject.Find ("Spine1");
		body [11] = GameObject.Find ("Spine");
		body [12] = GameObject.Find ("Hips");
		body [13] = GameObject.Find ("Scalp");
		body [14] = GameObject.Find ("HeadTop_End");
		body [15] = GameObject.Find ("R_Temple");
		body [16] = GameObject.Find ("L_Temple");
		body [17] = GameObject.Find ("RightForeArm");
		body [21] = GameObject.Find ("RightHand");
		body [23] = GameObject.Find ("RightHandIndex1");
		body [24] = GameObject.Find ("RightHandThumb2");
		body [25] = GameObject.Find ("RightHandPinky2");
		body [26] = GameObject.Find ("LeftForeArm");
		body [30] = GameObject.Find ("LeftHand");
		body [32] = GameObject.Find ("LeftHandIndex1");
		body [33] = GameObject.Find ("LeftHandThumb2");
		body [34] = GameObject.Find ("LeftHandPinky2");
		body [35] = GameObject.Find ("RightLed");
		body [38] = GameObject.Find ("RightFoot");
		body [41] = GameObject.Find ("RightFootToeBase_End");
		body [42] = GameObject.Find ("RightToeBase");
		body [45] = GameObject.Find ("LeftLed");
		body [48] = GameObject.Find ("LeftFoot");
		body [51] = GameObject.Find ("LeftFootToeBase_End");
		body [53] = GameObject.Find ("LeftToeBase");

		StreamReader reader = new StreamReader ("Suj01_PI_DP_C00_1.txt"); 
		
		using (reader) { 
			
			string line = " "; 
			int lineNumber = 10; 

				for (int i = 0; i < lineNumber; i++) 
				{ 
					line = reader.ReadLine(); 
					if (line == null) return; 
				}

			string line_10;
			line_10 = line; 
			string[] names = line_10.Split (new String[] {",",",,,"},StringSplitOptions.RemoveEmptyEntries); 

			nv_data = new Data_struct[names.Length] ;

				for (int i =0 ; i< names.Length; ++i )
				{
					nv_data[i] = new Data_struct () ;
					nv_data[i].marker_name = names[i] ; 
				}

			line = reader.ReadLine();
			string line_11;
			 line_11 = line;
			string[] axes = line_11.Split(new String[] {"Field #",","},StringSplitOptions.RemoveEmptyEntries);

			datas = new string[4000][]; 

			int counter = 0;
			while (line != null) { 
				counter++;
				line = reader.ReadLine();

				if (line == "ANALOG") 
				break ;

				if ((counter %3) != 1) 
					continue;

				string lines_datas; 
				lines_datas = line;
				datas[cpt] = lines_datas.Split(new string[] {","},StringSplitOptions.RemoveEmptyEntries);

				line = reader.ReadLine(); 

				cpt ++ ;

			}

				for (int i = 0 ; i < cpt ; ++i ) 
				{
					for (int j = 1 ; j < names.Length+1 ; j++ ) 
				{
					nv_data[j-1].positions = new Vector3[cpt]; 

				nv_data[j-1].positions[i].x = float.Parse(datas[i][j*3-2]); 
				nv_data[j-1].positions[i].y = float.Parse(datas[i][j*3-1]);
				nv_data[j-1].positions[i].z = float.Parse(datas[i][j*3]);

				}

			}

		}
		
	 }

	// Update is called once per frame
	void Update () {

		for (int i = 0; i < cpt; ++i) {
			for (int k = 0; k < body.Length; ++k)
			{
				if(body == null)
					Debug.Log("body is null!");

				if(body[k] == null)
					Debug.Log("body["+k+"] is null!");
				
				if(body[k].transform == null)
					Debug.Log("body["+k+"].transform is null!");		
				
				if(nv_data == null)
					Debug.Log("nv_data is null!");
				
				if(nv_data[k] == null)
					Debug.Log("nv_data["+k+"] is null!");
	
				body[k].transform.position = nv_data[k].positions[i];
				Debug.Log(body[1].transform.position);
			}

		}

	}

}



我的问题出现了在void update()中:



我的第一个问题是:body [k] .transform.position = nv_data [k] .positions [i];

此行的标题中会显示此问题的标题。



我试图找到问题,所以我有使用了不同的Debug.Log。出现的错误是:



body [1]为空!所以我的问题是关于身体[k]

nv_data是空的!所以我的问题是关于nv_data(当我停止动画时出现)

对象引用未设置为对象的实例为行:if(body [k] .transform == null )



你能帮我吗?



谢谢



Ps:我不是英语,我是C#的初学者

推荐答案

好的,让我吧给你一个'可能'的解决方案:



1 - 如果有很多可以保存的值,而且知之甚少,请不要使用矩阵。我宁愿使用DataTable。它允许添加大量数据并在以后获得有序值。



我写了一些与你的结构相对应的文本文件,事实上,假设这是正确的格式。



在使用您自己的文本文件之前,请确保它与正确的架构匹配。



Ok, let me give you a 'possible' solution:

1-If there are a lot of, and not well-know, of possible values to save, don't use a matrix. I'd rather use a DataTable. It allows to add a lot of data and get ordered values later.

I write some textfile corresponding to your structure, in fact, assuming this is the correct format.

Before to use your own text file be sure it match the correct schema.

Suj01_PI_DP_C00_1
Date:,2014/11/06
Time:,14:55:12
Type:,test
Description:,""
Notes:,""
 
TRAJECTORIES
100.000000,Hz
,Suj01:RIAS,,,Suj01:LIAS,,,Suj01:LIPS
Field #,X,Y,Z,X,Y,Z,X,Y,Z,X,Y,Z,X
1,-242.807816,1106.551270,1097.119385,14.437944,1075.778687,1097.119385,14.437944,1075.778687
100.000000,Hz
,Suj01:RIAS,,,Suj01:RIPS,,,Suj01:LIPS
Field #,X,Y,Z,X,Y,Z,X,Y,Z,X,Y,Z,X
3,-242.807816,1106.551270,1097.119385,14.437944,1075.778687,1097.119385,14.437944,1075.778687
100.000000,Hz
,Suj01:RIAS,,,Suj01:DSTR,,,Suj01:C7
Field #,X,Y,Z,X,Y,Z,X,Y,Z,X,Y,Z,X
1,-242.807816,1106.551270,1097.119385,14.437944,1075.778687,1097.119385,14.437944,1075.778687
100.000000,Hz
,Suj01:LIAS,,,Suj01:LIPS,,,Suj01:C7
Field #,X,Y,Z,X,Y,Z,X,Y,Z,X,Y,Z,X
5,-242.807816,1106.551270,1097.119385,14.437944,1075.778687,1097.119385,14.437944,1075.778687




这是代码:





And this is the code:

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

namespace test1
{
	class Program
	{
		static int Main(string[] args)
		{
			// define one table and it schema
			//
			System.Data.DataTable tdata = new System.Data.DataTable();
			tdata.Columns.Add("Name", typeof(string));
			tdata.Columns.Add("X", typeof(double));
			tdata.Columns.Add("Y", typeof(double));
			tdata.Columns.Add("Z", typeof(double));

			System.IO.StreamReader reader = new System.IO.StreamReader(@"..\..\TextFile1.txt");

			string line = "", captions = "", values = "";
			bool wrong_header = false;
						
			using ( reader )
			{
				// document header, Date, Time, etc... 
				// Do you need to save this info?
				//
				for (int x = 0; x < 8; x++)
				{
					if ((line = reader.ReadLine()) == null)
					{
						wrong_header = true;
						break;
					}
				}

				// header error,
				//
				if (wrong_header)
				{
					// error msg.....
					//
					return -1;
				}

				// i supouse this 4 lines always repeats
				//
				while (true)
				{
					// 100.0000,Hz
					if ((line = reader.ReadLine()) == null) break;

					// caption
					if ((captions = reader.ReadLine()) == null) break;

					// X,Y,Z stuff
					if ((line = reader.ReadLine()) == null) break;

					// values
					if ((values = reader.ReadLine()) == null) break;

					// split captions and values
					// as far I can see ",,," is the separator value
					string[] scap = captions.Split(new string [] {",,,"}
													, StringSplitOptions.RemoveEmptyEntries);
					string[] sval = values.Split(new char [] {','});

					// save every sample
					int pos_value = 0;
					foreach(string caption in scap)
					{
						System.Data.DataRow row = tdata.NewRow();

						// remove leading ','
						row["Name"] = caption.Substring(1, caption.Length - 1);
						// if you want to remove Sju01:
						// row["Name"] = caption.Substring(7, caption.Length - 1);

						// it must be 3 values (x,y,z) for every captin
						row["X"] = Convert.ToDouble(sval[pos_value++]);
						row["Y"] = Convert.ToDouble(sval[pos_value++]);
						row["Z"] = Convert.ToDouble(sval[pos_value++]);

						// add the row to the table
						tdata.Rows.Add(row);
					}
				}
			}

			// now you have a table in this form
			//
			// 'RIAS',X,Y,Z
			// 'RIAS',X,Y,Z
			// 'LIAS',X,Y,Z
			// 'LIPS',X,Y,Z
			// 'C7',X,Y,Z
			// 'DSTR',X,Y,Z

			// how to get all data ordered by name
			//
			Console.WriteLine("Ordered by name");
			System.Data.DataRow[] v_order_by_name = tdata.Select("", "Name");
			foreach(System.Data.DataRow rsort in v_order_by_name)
			{
				string msg = string.Format("{0}: {1},{2},{3}", rsort[0],rsort[1],rsort[2],rsort[3]);
				Console.WriteLine(msg);
			}
			Console.WriteLine();
			Console.WriteLine();

			// how to get data filtered by name
			//
			Console.WriteLine("Filtered by name RIAS");
			System.Data.DataRow[] v_filtered_by_name = tdata.Select("Name = 'Suj01:RIAS'", "");
			foreach (System.Data.DataRow rfilter in v_filtered_by_name)
			{
				string msg = string.Format("{0}: {1},{2},{3}", rfilter[0], rfilter[1], rfilter[2], rfilter[3]);
				Console.WriteLine(msg);
			}


			Console.WriteLine("Press any key.");
			Console.ReadKey();

			return 0;
		}
	}
}





这就是结果:





And this is the result:

Ordered by name
Suj01:LIAS: 5,-242.807816,1106.55127
Suj01:RIAS: 1,-242.807816,1106.55127
Suj01:RIAS: 3,-242.807816,1106.55127
Suj01:RIAS: 1,-242.807816,1106.55127
uj01:C7: 1097.119385,14.437944,1075.778687
uj01:C7: 1097.119385,14.437944,1075.778687
uj01:DSTR: 1097.119385,14.437944,1075.778687
uj01:LIAS: 1097.119385,14.437944,1075.778687
uj01:LIPS: 1097.119385,14.437944,1075.778687
uj01:LIPS: 1097.119385,14.437944,1075.778687
uj01:LIPS: 1097.119385,14.437944,1075.778687
uj01:RIPS: 1097.119385,14.437944,1075.778687


Filtered by name RIAS
Suj01:RIAS: 1,-242.807816,1106.55127
Suj01:RIAS: 3,-242.807816,1106.55127
Suj01:RIAS: 1,-242.807816,1106.55127
Press any key.





我希望它帮助你。



Salut



I hope it helps you.

Salut


这是我对你班级的改编......如果你需要的话,这一行读取每一行每隔四个,只需调用line = reader.ReadLine(),增加在循环外部实例化的计数器,然后在进行任何解析检查之前是否计数器%your_constant == 0.



Here is my adaptation of your class...this one reads each line, if you need every fourth, simply call line = reader.ReadLine(), increase the counter instantiated outside of the loop and before doing any parsing check if counter % your_constant == 0.

using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

public class Recup_donnees_3 : MonoBehaviour {
  // When the script instance is being loaded
  void Awake ()
  {
    Application.targetFrameRate = 25; // J'indique que la fréquence est de 25 Hz
  }

  class FileReader
  {
    static void Main()
    {
    // ------------- This first part allows me to read in the console and to load in a matrix 1 line / 4 from the 12th line of the text file to the end ------------- //
    // Create an instance of StreamReader to read from a file
    StreamReader reader = new StreamReader ("Suj01_PI_DP_C00_1.txt");

    using (reader) { // Automatic Closing of the Stream after working with it , otherwise we would have to write "reader.Close" at the end to close the stream, beneath the last command's line of this part "class FileReader"

      int lineNumber = 10;
    string line;
      // skip first 10 lines
      for (i = 0; i < lineNumber; i++) {

        line = reader.ReadLine();
        if (line == null) return; // this ensures that the file has at least 12 lines
    }

      // at this point our line contains row #10 (Suj01:RIAS,,,Suj01:LIAS,,,Suj01:LIPS,,,Suj01:RIPS,,,Suj01:DSTR,,,Suj01:C7,,,Suj01:RACR,,,)
      // do whatever you need to do
    string[] Matrice_Suj01_PI_DP_C00_1; // To create a matrix which contains 1 line / 4 from text file
    Matrice_Suj01_PI_DP_C00_1 = line;
    string[] values_position_X_Y_Z = Matrice_Suj01_PI_DP_C00_1.Split(',',3); // Pb : we can't use "Split" when it's a string []

    line = reader.ReadLine(); // here it is line #11 (Field #,X,Y,Z,X,Y,Z,X,Y,Z,X,Y,Z,X)
    // parse it and use it however you need
    line_11 = line;
    string[] axes = line_11.Split(new char[] {'Filed #',','}); // Every axe is separating by ',' and the first is writing behind 'Filed #,'

    line = reader.ReadLine(); // here the loop starts getting data

    int counter = 0;
    while (line != null) {
        counter++;
        if (counter % 4) != 1 continue;
    // here you're beginning with the lines you need ot enter into the matrix
    // (1,-242.807816,1106.551270,1097.119385,14.437944,1075.778687,)
    // Do whatever you need to do with the line data

    line = reader.ReadLine(); // after you're done, this needs to be last line in the while so you can continue the loop
      }
    }
  }
}


这篇关于C#对象引用未设置为Object的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆