2016-03-05 217 views
0

我使用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)命令獲得輸出,所以我在這裏丟失了一些東西。任何幫助都會很棒。

+1

你開始中創建一個新的文本變量。 「全局」文本不會被分配,並且本地文本在啓動結束時被銷燬。刪除開始內部文本前面的字符串。而且兩個都是在開始時完成的,你不能確定哪個會先運行。 – Everts

+0

從Unity Inspector窗格中爲公共「textFile」分配一個文件。這個分配的文件是一個CSV文件。我需要從CreateLevel類訪問這個組件,我不認爲我是從上面的初始版本開始的。我會在下面的評論中寫下解決方案。 – user6020789

回答

0

下面是最終的解決方案。我認爲我的問題是公共TextAsset(「textFile」變量)沒有從CreateLevel類訪問。請參閱YouTube上的AwfulMedia教程:Unity C#教程 - 訪問其他類(第5部分)。我希望這不會降級我堆棧溢出,只是想在應得的功勞。我接受了這個教程併爲我的目的進行了修改。

這裏是新的ReadText類:

public class ReadText: MonoBehaviour { 
    public TextAsset textFile; 
    //text file to be read is assigned from the Unity inspector pane after selecting 
    //the object for which this C# class is attached to 

    string Start(){ 
     string text = textFile.text; //this is the content as string 
     Debug.Log(text); 
     return text; 
    } 
} 

而且新CreateLevel類

public class CreateLevel : MonoBehaviour { 
    //variables needed for reading text from the level design CSV file 
    private ReadText readTextComponent; 
    public GameObject LevelDesigner; 
    public string fileString; 

    // Use this for initialization 
    void Start() { 
     readTextComponent = LevelDesigner.GetComponent<ReadText>(); 
     fileString = readTextComponent.textFile.text; 
     //accesses the public textFile declared in the ReadText class. Assigns the textFile 
     //text string to the CreateLevel class fileString variable 

    } 
}