Unity 设置配置项文件

问题:将一些脚本参数使用配置文件进行赋值,避免打包后修改一些值还需要再次打包。

实现:

在根目录 Assets下创建 StreamingAssets 文件夹,然后在该文件夹下存放配置文件即可,该文件夹下的配置文件不会进行打包,所以项目构建打包后还可以进行修改配置文件内容。

我这里使用了 JSON 格式的文件。我这里存放了一个https的请求地址。

{
    "Base":{
        "apiBaseUrl": "http://xxx.com/"
    }
}

获取配置文件后就直接存储到 configuration 中,其他脚本先引入ConfigManger类,直接ConfigManger.configuration.apiBaseUrl就可以调用值。

脚本示例:

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

public class ConfigManger : MonoBehaviour
{
    public Configuration configuration;
    // Start is called before the first frame update
    void Start()
    {
        LoadConfig();
    }

    private void LoadConfig()
    {
        string filePath = Path.Combine(Application.streamingAssetsPath, "config.json");

        if (File.Exists(filePath))
        {
            string json = File.ReadAllText(filePath);
            configuration = JsonUtility.FromJson<Configuration>(json);

            Debug.Log("配置文件加载成功!");
            // 在这里使用其他配置项  
        }
        else
        {
            Debug.LogError("配置文件未找到!");
        }
    }


    [System.Serializable]
    public class Configuration
    {
        public BaseConfig Base;

    }

    [System.Serializable]
    public class BaseConfig
    {
        public string apiBaseUrl;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值