配置文件管理

介绍

配置文件用于实现数据可外部配置的能力,在程序打包后,可以在外部更改相关数据使程序更符合项目需求。

创建配置文件

Develop/Scripts/Configs目录下, 右键执行Create/UNIHper/ConfigScript,输入配置文件名GameConfig,即创建了一个配置文件类,在程序运行时,配置文件类会与本地实体文件进行同步。

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

using UNIHper;

[SerializedAt(AppPath.StreamingDir)]    // 文件保存位置
[SerializeWith(ConfigDriver.XML)]       // 配置文件驱动 YAML/XML/JSON
public class GameConfig : UConfig
{
    // 此处添加需要的变量
    public float LongTimeNoOperationTimeout = 60f;
    public string PlayerName = "Player";

    // Write your comments here
    protected override string Comment()
    {
        return @"
        LongTimeNoOperationTimeout: 长时间无操作超时时间
        PlayerName: 玩家名称
        ";
    }

    // Called once after the config data is loaded
    protected override void OnLoaded() { }
}

使用配置文件

SceneEntryScript.cs
using System.IO;
using UnityEngine;
using UNIHper;

public class SceneEntryScript : SceneScriptBase
{
    // Called once after scene is loaded
    private void Start()
    {
        // 获取长时间无操作超时时间
        var longTimeNoOperationTimeout = Managements.Config
            .Get<GameConfig>()
            .LongTimeNoOperationTimeout;
        // 获取玩家名称
        var playerName = Managements.Config.Get<GameConfig>().PlayerName;

        // 更改玩家名称
        Managements.Config.Get<GameConfig>().PlayerName = "New Player Name";
        // 保存配置
        Managements.Config.Serialize<GameConfig>();
    }
}

同步后的本地文件

GameConfig.xml
<?xml version="1.0"?>
<GameConfig xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <!--
        LongTimeNoOperationTimeout: 长时间无操作超时时间
        PlayerName: 玩家名称
        -->
  <LongTimeNoOperationTimeout>60</LongTimeNoOperationTimeout>
  <PlayerName>New Player Name</PlayerName>
</GameConfig>

Last updated