Unity 数据存储

1 PlayerPrefs
DeleteAll Removes all keys and values from the preferences. Use with caution.
DeleteKey Removes key and its corresponding value from the preferences.
GetFloat Returns the value corresponding to key in the preference file if it exists.
GetInt Returns the value corresponding to key in the preference file if it exists.
GetString Returns the value corresponding to key in the preference file if it exists.
HasKey Returns true if key exists in the preferences.
Save Writes all modified preferences to disk.
SetFloat Sets the value of the preference identified by key.
SetInt Sets the value of the preference identified by key.
SetString Sets the value of the preference identified by key.
2 文本 后缀为 .txt
(1)

    public class ExampleClass : MonoBehaviour {
        public TextAsset asset;
        void Start() {
            print(asset.text);
        }
    }

(2)

    TextAsset text = (TextAsset)Resources.Load("Map1");
    if (text != null) {
        Debug.Log (text.text);
    } else {
        Debug.Log("text is null");
    }

3 使用json
下载LitJson.dll 地址:http://lbv.github.io/litjson/ 开源
Project中 Import New Assets 添加进LitJson.dll
脚本中加入 using LitJson;

    /// 数据保存
    /// </summary>
    /// <param name="tobject">Tobject.</param>
    /// <param name="path">;Path.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public void Save (object tobject, string path)
    {
        string serializedString = JsonMapper.ToJson (tobject);
        using (StreamWriter sw = File.CreateText(path)) {
            sw.Write (serializedString);
        }

    }

    /// 载入数据
    /// </summary>
    /// <param name="path">;Path.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public T Load<T> (string path)
    {
        if (File.Exists (path) == false)
            return default(T);
        using (StreamReader sr = File.OpenText(path)) {
            string stringEncrypt = sr.ReadToEnd ();
            if (string.IsNullOrEmpty (stringEncrypt))
                return default(T);
            return  JsonMapper.ToObject<T> (stringEncrypt);
        }
    }

调用举例:
1

        SAVE
        public List<string> NotifyString;
        private string LOADING_DATA_CONFIG_URL; 
        LOADING_DATA_CONFIG_URL = Application.persistentDataPath+ @"/LoadNotify.data";
        NotifyString = new List<string> ();
        NotifyString.Add(LOADING_DATA_CONFIG_URL);
        Save(NotifyString,LOADING_DATA_CONFIG_URL);
        LOAD
        List<string> stringList = Load<List<string>> (LOADING_DATA_CONFIG_URL);

2

        public class Hero{
            public string name;
        }
        SAVE
        private string LOADING_DATA_CONFIG_URL; 
        LOADING_DATA_CONFIG_URL = Application.persistentDataPath+ @"/LoadNotify.data";
        Hero hero = new Hero();
        hero.name = LOADING_DATA_CONFIG_URL;
        Save(hero,LOADING_DATA_CONFIG_URL);
        LOAD
        Hero hero = Load<Hero> (LOADING_DATA_CONFIG_URL);

** 注意保存时只能创建文件,如果写入不同目录需要创建目录,然后创建文件

JSON 存储代码

using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
using System.Collections.Generic;

public class Hero{
    public string name;
}

public class GamePanel : MonoBehaviour {

    public UILabel mLable;
    public UIButton mButton;
    //      public List<string> NotifyString;
    private string LOADING_DATA_CONFIG_URL; 
    // Use this for initialization
    void Start () {
        LOADING_DATA_CONFIG_URL = Application.temporaryCachePath+ @"/LoadNotify.data";
        Hero hero = new Hero();
        hero.name = LOADING_DATA_CONFIG_URL;
        //      NotifyString = new List<string> ();
        //      NotifyString.Add (LOADING_DATA_CONFIG_URL);
        Save(hero,LOADING_DATA_CONFIG_URL);
        if (mButton != null) {
            mButton.gameObject.AddComponent<UIEventListener>();
            UIEventListener.Get (mButton.gameObject).onClick = ClickSprite;
        }
    }

    private void ClickSprite(GameObject go){
        //      List<string> stringList = Load<List<string>> (LOADING_DATA_CONFIG_URL);
        Hero hero = Load<Hero> (LOADING_DATA_CONFIG_URL);
        if (mLable != null) {
            mLable.text = hero.name;
        }
    }

    // Update is called once per frame
    void Update () {

    }

    /// 数据保存
    /// </summary>
    /// <param name="tobject">Tobject.</param>
    /// <param name="path">;Path.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public void Save (object tobject, string path)
    {
        string serializedString = JsonMapper.ToJson (tobject);
        using (StreamWriter sw = File.CreateText(path)) {
            sw.Write (serializedString);
        }

    }

    /// 载入数据
    /// </summary>
    /// <param name="path">;Path.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public T Load<T> (string path)
    {
        if (File.Exists (path) == false)
            return default(T);
        using (StreamReader sr = File.OpenText(path)) {
            string stringEncrypt = sr.ReadToEnd ();
            if (string.IsNullOrEmpty (stringEncrypt))
                return default(T);
            return  JsonMapper.ToObject<T> (stringEncrypt);
        }
    }
}
Unity中,有几种数据存储的方法可以使用。其中包括使用API保存数据、使用SessionState存储会话状态和使用EditorPrefs存储偏好设置。 使用API保存数据是在项目中共享数据的一种方法。保存的数据会被加密,并适合保存个人信息或密码等敏感信息。在Unity中,数据保存在项目的UserSettings目录下的EditorUserSettings.asset文件中。旧版本存储在Library的EditorUserSettings.asset文件中。可以使用静态函数SetConfigValue来设置给定键标识的项的单个字符串值,使用GetConfigValue来获取与键对应的值(如果存在)。 另一种方法是使用SessionState存储会话状态。SessionState是一种键/值存储,旨在在重新加载程序集期间保留Editor会话状态。退出Unity时,系统会清除SessionState中存储的状态信息。可以使用静态函数来擦除、检索和存储布尔值、浮点值、整数值、整数数组、字符串值和Vector3值。 还有一种方法是使用EditorPrefs存储偏好设置。在macOS上,EditorPrefs存储在~/Library/Preferences/com.unity3d.UnityEditor5.x.plist文件中。在Windows上,EditorPrefs存储在注册表中的HKCU\Software\Unity Technologies\UnityEditor 5.x键下。可以使用静态函数来删除、检索和存储布尔值、浮点值、整数值和字符串值。 所以,Unity提供了多种数据存储的方式,可以根据具体需求选择适合的方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Unity用于储存数据的几种方式](https://blog.csdn.net/u012685176/article/details/127980850)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值