How to avoid hard code (C #) in unity3D Projects #),
In normal times, hard code is not allowed in the Code. How do we deal with it? So what is hard code?
We call it hard code: eg: 1 public UIlabel label; 2 label. text = "Welcome to dreamland"; this is commonly known as hard code.
Well, how can we avoid it? Let's just say nothing:
This is a processing method. TXT format document, with the ID in front and descriptive text in the back.
But how can we access the data in this txt file in the project? If you don't talk much about it, go directly to the Code:
1 using UnityEngine; 2 using System.Collections; 3 4 public class ReadTxt :MonoBehaviour{ 5 6 public TextAsset txt; 7 public static ReadTxt _instance; 8 string fonttxt; 9 void Awake() 10 {11 _instance = this;12 }13 14 void Start() { }15 16 public string GetFont(int ID)17 {18 string[] taskinfoArray = txt.ToString().Split('\n');19 foreach(string str in taskinfoArray){20 21 string[] Fontlist = str.Split('|');22 int id = int.Parse(Fontlist[0]);23 while (ID== id) {24 fonttxt = Fontlist[1];25 break;26 }27 }28 29 return fonttxt;30 }31 32 33 }
We will not go into details about the Single-Profit Mechanism.
String [] taskinfoArray = txt. toString (). split ('\ n'); here some friends will ask, what is Split (' \ n'), which is a segmentation function to check whether there is any line feed operation, if a line feed exists in the array,
In the above txt document, we will write a line, and we must press enter to write a line break. Here we use this Split () function for detection.
Now, everyone knows about it. As for calling, this is very simple.
1 using UnityEngine; 2 using System.Collections; 3 4 public class TestTxt : MonoBehaviour { 5 6 public UILabel label; 7 8 9 void Start() 10 {11 string bbb = ReadTxt._instance.GetFont(1001);12 13 label.text = bbb;14 }15 16 }
However, the text displayed by the label must be: Maintenance announcement. Here we are just a reference, so the writing is rough and I hope you will understand.