Home > Software engineering >  How do I create something to store and execute code as if it were in a array? (In unity)
How do I create something to store and execute code as if it were in a array? (In unity)

Time:08-04

I want to create something to store code like an array.

Example code:

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.

Any amount of help will be appreciated!

CodePudding user response:

The way unity saves data:

  1. PlayerPrefs unity3d provides a class for local persistent saving and reading -------PlayerPrefs. The working principle is very simple, the data is saved in the file in the form of key-value pairs, and then the program can take out the file according to this name. The Playerprefs class supports saving and reading of 3 data types, namely floating point, integer and string.

     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. Read ordinary text resources: TextAsset.

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

    Create a Resources folder in the root directory of the Project window, and then put the file in the folder named unity3d.txt under the Resources folder to read it.

  3. Json.

    JSON syntax rules.

    (1) Objects are represented as key-value pairs.

      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) Data is separated by commas.

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

    (3) Curly braces save the object.

    (4) Square brackets save the array.

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

CodePudding user response:

If you want to store datas on Runtime only, You can create en empty object on scene like DataController and add a script on the object like "DataStore".

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

Then you can react this object and script with tag or reference to use or change this array.

private DataStore dataStore;

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