问题:将一些脚本参数使用配置文件进行赋值,避免打包后修改一些值还需要再次打包。
实现:
在根目录 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;
}
}