unity遊戲框架學習-用戶設置

概述:http://www.javashuo.com/article/p-nggymcxb-bw.htmlhtml

遊戲設置用於保存玩家的遊戲設置,例如玩家但願關掉音樂、音效啥的。當玩家設置完後,第二次登陸能夠保持以前的設置。例如如下選項json

 

保存玩家設置有兩種方式c#

1.保存在本地,能夠是json、xml、txt等全部能夠讀取的文件格式,也能夠使用unity的PlayerPrefs進行保存。不須要佔用網絡資源,缺點是用戶更換手機、卸載重裝、清理遊戲緩存都會致使設置丟失。緩存

2.上傳到服務器。優勢是不會丟失,缺點是須要佔用網絡資源,須要在服務器保存數據。服務器

具體使用哪一種方式由策劃大大決定。網絡

 

具體實現:其實原理就是用一個容器存儲設置(鍵值對),在遊戲開始時載入設置,在遊戲結束時保存設置。session

1、c#端:這邊示例使用unity的PlayerPrefs進行本地存儲ui

1.消息定義:lua

/// <summary>
/// 全部設置名字都在這裏定義 爲了知道遊戲中全部的本地緩存數據 避免重複定義
/// </summary>
public enum UserSettingDefeine
{
    MUSIC_SWITCH ,                // 音樂開關
    SOUND_SWITCH ,                // 音效開關

    USER_LEVEL,                    // 玩家等級
}

2.消息保存、獲取。在遊戲登陸時調用Load加載設置,在遊戲退出時調用Save保存設置。spa

using System;
using System.Collections.Generic;
using UnityEngine;
using SRF;

/// <summary>
/// 用戶設置,key在UserSettingDefeine定義
/// </summary>
public static class UserSetting
{
    static string SettingKey = "SETTING";
    private static Dictionary<int, string> settings = null;

    public static void Load()
    {
        // 加載配置
        settings = new Dictionary<int, string>();
        
        if (PlayerPrefs.HasKey(SettingKey))
        {
            string jsonString = PlayerPrefs.GetString(SettingKey);
            settings = Json.Deserialize(jsonString) as Dictionary<int, string>;
        }

        //test
        //bool music = GetBool(UserSettingDefeine.MUSIC_SWITCH, true);
        //SetBool(UserSettingDefeine.MUSIC_SWITCH, music);

        //int level = GetValue(UserSettingDefeine.USER_LEVEL, 1);
        //SetValue(UserSettingDefeine.USER_LEVEL, level);
    }

    public static void Save()
    {
        // 保存配置
        string json = Json.Serialize(settings);
        PlayerPrefs.SetString(SettingKey, json);
        PlayerPrefs.Save();
    }

    #region 獲取玩家設置
    public static int GetInt(UserSettingDefeine key, int defaultVal = 0)
    {
        string val = null;
        int intKey = (int)key;

        if (settings.TryGetValue(intKey, out val))
            return System.Convert.ToInt32(val);
        settings[intKey] = defaultVal.ToString();
        return defaultVal;
    }

    public static float GetFloat(UserSettingDefeine key, float defaultVal = 0f)
    {
        string val = null;
        int intKey = (int)key;

        if (settings.TryGetValue(intKey, out val))
            return System.Convert.ToSingle(val);
        settings[intKey] = defaultVal.ToString();
        return defaultVal;
    }

    public static bool GetBool(UserSettingDefeine key, bool defaultVal = false)
    {
        string val = null;
        int intKey = (int)key;

        if (settings.TryGetValue(intKey, out val))
            return System.Convert.ToBoolean(val);
        settings[intKey] = defaultVal.ToString();
        return defaultVal;
    }

    public static string GetString(UserSettingDefeine key, string defaultVal = "")
    {
        string val = null;
        int intKey = (int)key;

        if (settings.TryGetValue(intKey, out val))
            return val.ToString();
        settings[intKey] = defaultVal.ToString();
        return defaultVal;
    }
    #endregion

    #region 設置玩家設置
    public static void SetInt(UserSettingDefeine key, int val)
    {
        settings[(int)key] = val.ToString();
    }

    public static void SetFloat(UserSettingDefeine key, float val)
    {
        settings[(int)key] = val.ToString();
    }

    public static void SetBool(UserSettingDefeine key, bool val)
    {
        settings[(int)key] = val.ToString();
    }

    public static void SetString(UserSettingDefeine key, string val)
    {
        settings[(int)key] = val;
    }
    #endregion

    /// <summary>
    /// 設置玩家設置
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>設置id
    /// <param name="val"></param>
    public static void SetValue<T>(UserSettingDefeine key, T val)
    {
        settings[(int)key] = val.ToString();
    }

    /// <summary>
    /// 獲取玩家設置信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>設置id
    /// <param name="defaultVal"></param>默認值,必傳
    /// <returns></returns>
    public static T GetValue<T>(UserSettingDefeine key, T defaultVal)
    {
        string val = null;
        int intKey = (int)key;

        if (settings.TryGetValue(intKey, out val))
        {
            if (defaultVal is int)
            {
                return (T)Convert.ChangeType(Convert.ToInt32(defaultVal), typeof(T));         
            }
            else if (defaultVal is float)
            {
                return (T)Convert.ChangeType(Convert.ToSingle(defaultVal), typeof(T));
            }
            else if (defaultVal is bool)
            {
                return (T)Convert.ChangeType(Convert.ToBoolean(defaultVal), typeof(T));
            }
            else
            {
                return (T)Convert.ChangeType(Convert.ToString(defaultVal), typeof(T));
            }
        }
            
        settings[intKey] = defaultVal.ToString();
        return defaultVal;
    }
}

 

2、lua端(這邊示例保存服務端)

在遊戲開始時,服務器會同步玩家設置信息。玩家更改設置後,會調用服務器接口進行保存。

local PlayerSettingCtrl = class("PlayerSettingCtrl", LogicCtrlBase)
local json = require("cjson")
local SettingUtil = SettingUtil

function PlayerSettingCtrl:ctor()
    PlayerSettingCtrl.super.ctor(self)
    self._isInitGameSetting = false
    self._settingData = {}
    self._gameSettingData = {}
end

function PlayerSettingCtrl:Init()
    PlayerSettingCtrl.super.Init(self)

    local NetMsg = NetMsg
    NetMsg.Register("playersetting_init_syn", self, self.OnSyncPlaySetting)
end

-- 同步玩家設置 -- 保存PlayerSettingDefine.SettingType的數據
function PlayerSettingCtrl:OnSyncPlaySetting(data, session)
for _, v in pairs(data.playersettinginfolist) do
self._settingData[v.key] = json.decode(v.value)
end
end
function PlayerSettingCtrl:ClearData() 
  self._settingData
= {}
end

--獲取玩家設置,若是有傳默認值,則會自動建立記錄 ---- 若是value是table類型,不要修改這個值(本身拷貝一份)
function PlayerSettingCtrl:GetSettingValue(key, defaultValue)
  local value
= self._settingData[key]
  if value == nil and defaultValue ~= nil then
    value
= defaultValue self:ReqChangePlaySetting(key, value)
  self._settingData[key]
= defaultValue
  end
  return value
end

---endregion ---region 請求 -- 請求更改玩家設置
function PlayerSettingCtrl:ReqChangePlaySetting(settingType, value)
  self._settingData[settingType]
= value
  local valueStr
= json.encode(value)
  local data
= {key = settingType, value = valueStr}
  NetMsg.SendMsg(
"playersetting_change_req", data, true)
end

---endregion

return PlayerSettingCtrl
相關文章
相關標籤/搜索