【问题标题】:How do I create something to hold and execute code as if it were in a array? (In unity)如何创建一些东西来保存和执行代码,就好像它在数组中一样? (统一)
【发布时间】:2022-08-19 12:00:58
【问题描述】:

我想创建一些东西来存储像数组这样的代码。

示例代码:

public code[] codeArray = { gameobject.SetActive(false),Debug.Log(\"Hello world\"),bool = true; };

private void Start()
{
    codeArray[2];
    codeArray[0];
    codeArray[1];
}

//Output bool = true, gameobject is not active, there is a \"Hello world\" in the log.

任何数量的帮助将不胜感激!

  • C++ 与其他语言非常不同。学习它的最佳方式是使用good C++ book。除了这不是有效的 C++ 语法之外,C++ 中的数组只能包含相同类型的元素。
  • 您可以拥有std::function<void()> codeArray[3];,然后用 lambda 填充它。
  • 您实际上是指 C# 而不是 C++ 吗? (错误的答案会让你得到非常不同且对你无用的答案。)
  • 哦!!哎呀,你的权利啊啊啊...感谢您的注意!
  • 你想存储实际的语句以便以后执行它们吗?

标签: c# visual-studio unity3d


【解决方案1】:

unity保存数据的方式:

  1. 播放器首选项 unity3d 提供了一个本地持久保存和读取的类-------PlayerPrefs。工作原理很简单,数据以键值对的形式保存在文件中,然后程序就可以根据这个名字取出文件了。 Playerprefs 类支持浮点、整数和字符串三种数据类型的保存和读取。

     PlayerPrefs.SetInt(); save integer data
    
     PlayerPrefs.SetFloat(); save floating point data
    
     PlayerPrefs.SetString(); save string data
    
     PlayerPrefs.GetInt(); read integer data
    
     PlayerPrefs.GetFloat(); read floating point data
    
     PlayerPrefs.GetString(); read string data
    
  2. 阅读普通文本资源:TextAsset。

     TextAsset text=(TextAsset)Resources.Load("unity3d");
     Debug.Log(text.text);
    

    在Project窗口的根目录下创建一个Resources文件夹,然后将文件放到Resources文件夹下名为unity3d.txt的文件夹中读取。

  3. 杰森。

    JSON 语法规则。

    (1) 对象表示为键值对。

      Dictionary<key,value> dic = new Dictionary<key,value>();
      dic[0] = "Jack";
      string temp = dic[0];
      Format: {"firstName": "Json"}
      {"firstName": "Jack"}
      The key-value pairs are connected by colons
    

    (2) 数据用逗号分隔。

     {"firstName": "Jack", "middleName": "Nigulas"}
    

    (3) 花括号保存对象。

    (4) 方括号保存数组。

     "People":[{"name":"Xiaohong","age":"16","grade":"2"},{"name":"Xiaoming","age":"18"," grade":"2"}]
    

【讨论】:

    【解决方案2】:

    如果您只想在运行时存储数据, 您可以在像 Data Controller 这样的场景中创建一个空对象,并在像“DataStore”这样的对象上添加一个脚本。

    Public class DataStore: MonoBehavior{
      public code[] codeArray = { gameobject.SetActive(false),Debug.Log("Hello world"),bool = true; };
    }
    

    然后,您可以使用标记或引用对该对象和脚本做出反应,以使用或更改该数组。

    private DataStore dataStore;
    
    void Start(){
      dataStore= GameObject.FindGameObjectsWithTag("DataController").GetComponent<DataStore>();
      Debug.Log(dataStore.codeArray[0]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多