zoukankan      html  css  js  c++  java
  • unity3D项目中如何避免硬代码(C#)

    平时做项目,代码中是不允许出现硬代码的,一般我们是怎么处理的呢? 那么硬代码又是什么呢?

    我们俗称的硬代码:eg:  1 public UIlabel label; 2 label.text = "欢迎来到梦幻岛";  这样我们俗称为硬代码。

    好了,那么该如何避免,话不多说,直接上图:

    这是一种处理方式,TXT 格式的文档,前面是ID,后面是描述性文字。

    可是我们该如何在项目中访问这个txt文件里面的数据呢? 话不多说,直接上代码:

     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('
    ');
    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 }

     上述用到了单利,单利这里我们就不赘述了。

    string[] taskinfoArray = txt.ToString().Split('
    ');  这里有些朋友就要问了,Split('
    ')是干什么的,它是分割函数,检测是否有换行操作,如果有换行我们把它存在数组里面,
    上面的txt文档,我们就是写完一行,肯定要回车换行写下一句,这里就是用这个Split()函数进行检测的。
      好了说到这里,想必大家都清楚了吧。至于调用呢,这个就很简单了。
     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 }

    然而label显示的 文字必定是:维护公告。  这里我们只是抛砖引玉,所以写的比较粗糙,望大家谅解。



  • 相关阅读:
    Java操作PDF之iText超入门
    Bootstrap 总结
    使用iframe框架后的页面跳转时目标页面变为iframe的子页面的问题
    Alluxio/Tachyon如何发挥lineage的作用?
    (转载)Zab vs. Paxos
    mysql批量数据导入探究
    读技术性文本的技巧
    Spark设计思想浅析
    MapReduce调优总结与拓展
    MapReduce 计算模式
  • 原文地址:https://www.cnblogs.com/zhaolaosan/p/4618010.html
Copyright © 2011-2022 走看看