unity游戏框架学习-用户设置

概述:https://www.cnblogs.com/wang-jin-fu/p/10975660.html

游戏设置用于保存玩家的游戏设置,例如玩家希望关掉音乐、音效啥的。当玩家设置完后,第二次登录可以保持之前的设置。例如以下选项

 

保存玩家设置有两种方式

1.保存在本地,可以是json、xml、txt等所有可以读取的文件格式,也可以使用unity的PlayerPrefs进行保存。不需要占用网络资源,缺点是用户更换手机、卸载重装、清理游戏缓存都会导致设置丢失。

2.上传到服务器。优点是不会丢失,缺点是需要占用网络资源,需要在服务器保存数据。

具体使用哪种方式由策划大大决定。

 

具体实现:其实原理就是用一个容器存储设置(键值对),在游戏开始时载入设置,在游戏结束时保存设置。

一、c#端:这边示例使用unity的PlayerPrefs进行本地存储

1.消息定义:

/// <summary>
/// 所有设置名字都在这里定义 为了知道游戏中所有的本地缓存数据 避免重复定义
/// </summary>
public enum UserSettingDefeine
{
    MUSIC_SWITCH ,                // 音乐开关
    SOUND_SWITCH ,                // 音效开关

    USER_LEVEL,                    // 玩家等级
}

2.消息保存、获取。在游戏登录时调用Load加载设置,在游戏退出时调用Save保存设置。

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;
    }
}

 

二、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

 

posted @ 2019-07-27 17:53  柯腾_wjf  阅读(1663)  评论(0编辑  收藏  举报