我使用Unity 5和mono開發進行C#編輯。我有一個C#文件,它讀取CSV文件並從CSV內的內容創建一個字符串。我把這個類作爲一個帶有公共字符串變量的公共類,因爲我想能夠在另一個類中訪問這個字符串變量。這裏的CSV閱讀器類:使用Unity 5訪問另一個C#類的公共變量
using UnityEngine;
using System.Collections;
using System.IO;
public class ReadText : MonoBehaviour{
public TextAsset textFile; // drop your file here in inspector
public string text = "";
void Start(){
string text = textFile.text; //this is the content as string
Debug.Log(text);
}
}
這個類的工作正常。按照預期,我在Unity控制檯上運行Debug.Log(文本)輸出。
下面是我試圖從訪問的ReadText類公共文本的其他類:
public class CreateLevel : MonoBehaviour {
void Start() {
//First, access the text that was read into the ReadText Class (from CSV file)
//Find the object "Level Designer" that has the ReadText.cs script attached to it
GameObject designer = GameObject.Find("LevelDesigner");
//Get a component of the ReadText Class and assign a new object to it
ReadText CSVText = designer.GetComponent<ReadText>();
//Now you can access the public text file String
string levelString = CSVText.text;
print(levelString);
//Second, identify each individual text, line by line. As each text symbol is identified
//place the corresponding sprite on the allocated space in the game scene
//When the & symbol is encoutered, go to the next line
//do all this while there are text symbols, once we have the "!" symbol, we're done
print(text);
print("We're inside of CreateLevel Class! :C)");
}
}
的CreateLevel C#文件附加到場景中的一個空對象。 Unity運行時沒有問題,但我沒有從Debug.Log或該類的print(text)命令獲得輸出,所以我在這裏丟失了一些東西。任何幫助都會很棒。
你開始中創建一個新的文本變量。 「全局」文本不會被分配,並且本地文本在啓動結束時被銷燬。刪除開始內部文本前面的字符串。而且兩個都是在開始時完成的,你不能確定哪個會先運行。 – Everts
從Unity Inspector窗格中爲公共「textFile」分配一個文件。這個分配的文件是一個CSV文件。我需要從CreateLevel類訪問這個組件,我不認爲我是從上面的初始版本開始的。我會在下面的評論中寫下解決方案。 – user6020789