使用Unity 5从另一个C#类访问公共变量

时间:2016-03-05 00:46:25

标签: c# unity5 public-method

我使用Unity 5和单色开发进行C#编辑。我有一个C#文件,它读取CSV文件并从CSV中的内容创建一个字符串。我使用公共字符串变量使这个类成为一个公共类,因为我希望能够在另一个类中访问这个字符串变量。这是CSV Reader类:

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 个答案:

答案 0 :(得分:0)

这是最终的解决方案。我认为我的问题是没有从CreateLevel类访问公共TextAsset(&#34; textFile&#34;变量)。感谢YouTube上的AwfulMedia教程:Unity C#Tutorial-访问其他类(第5部分)。我希望这不会降低我在Stack溢出时的评级,只是想给予应有的信用。我接受了教程并修改了我的目的。

这是新的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

    }
}