Unity 使用INI文件存储数据或配置参数预设

法1:调用外部C++api库

具体使用:

public class Ini{

    //读取INI文件需要调用C++的APP
    
    [System.Runtime.InteropServices.DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
    [System.Runtime.InteropServices.DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);
        
    private string iPath = null;
    public Ini(string path)
    {
        this.iPath = path;
    }

    /// <summary>
    /// 写数据
    /// </summary>
    /// <param name="section">配置节</param>
    /// <param name="key">键名</param>
    /// <param name="value">键值</param>
    public void WriteValue(string section, string key, string value)
    {  

        WritePrivateProfileString(section, key, value, iPath);

    }

    /// <summary>
    /// 读数据
    /// </summary>
    /// <param name="section">配置节</param>
    /// <param name="key">键名</param>
    /// <returns></returns>
    public string ReadValue(string section, string key)
    {
        // 每次从ini中读取多少字节 
        System.Text.StringBuilder temp = new System.Text.StringBuilder(255);        

        GetPrivateProfileString(section, key, "", temp, 255, iPath);

        return temp.ToString();

    }
}

public class Program
{
    public static void Main()
    {
        string filePath = Application.streamingAssetsPath + "/file.ini";
        string section = "SectionName";
        string key = "KeyName";

        // 读取 INI 文件
        string value = Ini.ReadValue(section, key, "", filePath);
        Console.WriteLine("Value: " + value);

        // 写入 INI 文件
        Ini.WriteValue(section, key, "NewValue", filePath);
        Console.WriteLine("Value written.");

        // 重新读取 INI 文件
        value = Ini.ReadValue(section, key, "", filePath);
        Console.WriteLine("Value: " + value);
    }
}

ini文本参考:

法2:使用System.IO命名空间的类:

具体使用:

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

class IniFile
{
    private readonly string filePath;
    private readonly Dictionary<string, Dictionary<string, string>> sections;

    public IniFile(string filePath)
    {
        this.filePath = filePath;
        this.sections = new Dictionary<string, Dictionary<string, string>>();
        Load();
    }

    public string GetValue(string section, string key)
    {
        if (sections.ContainsKey(section) && sections[section].ContainsKey(key))
        {
            return sections[section][key];
        }
        return null;
    }

    public void SetValue(string section, string key, string value)
    {
        if (!sections.ContainsKey(section))
        {
            sections[section] = new Dictionary<string, string>();
        }
        sections[section][key] = value;
        Save();
    }

    private void Load()
    {
        string currentSection = null;

        foreach (string line in File.ReadLines(filePath))
        {
            string trimmedLine = line.Trim();

            if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]"))
            {
                currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2);
                continue;
            }

            int equalsIndex = trimmedLine.IndexOf('=');
            if (equalsIndex > 0)
            {
                string key = trimmedLine.Substring(0, equalsIndex).Trim();
                string value = trimmedLine.Substring(equalsIndex + 1).Trim();

                if (!string.IsNullOrEmpty(currentSection) && !string.IsNullOrEmpty(key))
                {
                    if (!sections.ContainsKey(currentSection))
                    {
                        sections[currentSection] = new Dictionary<string, string>();
                    }
                    sections[currentSection][key] = value;
                }
            }
        }
    }

    private void Save()
    {
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            foreach (KeyValuePair<string, Dictionary<string, string>> section in sections)
            {
                writer.WriteLine($"[{section.Key}]");

                foreach (KeyValuePair<string, string> entry in section.Value)
                {
                    writer.WriteLine($"{entry.Key}={entry.Value}");
                }

                writer.WriteLine();
            }
        }
    }
}

public class Program
{
    public static void Main()
    {
        string filePath = Application.streamingAssetsPath + "/file.ini";
        string section = "SectionName";
        string key = "KeyName";

        IniFile iniFile = new IniFile(filePath);

        // 读取值
        string value = iniFile.GetValue("section", "key");
        Console.WriteLine(value);

        // 设置值
        iniFile.SetValue("Section2", "Key2", "Value2");       
        
    }
}
相关推荐
码农君莫笑1 小时前
使用blazor开发信息管理系统的应用场景
数据库·信息可视化·c#·.net·visual studio
可喜~可乐3 小时前
C# WPF开发
microsoft·c#·wpf
666和7777 小时前
C#的单元测试
开发语言·单元测试·c#
小码编匠8 小时前
WPF 星空效果:创建逼真的宇宙背景
后端·c#·.net
超龄魔法少女9 小时前
[Unity] ShaderGraph动态修改Keyword Enum,实现不同效果一键切换
unity·技术美术·shadergraph
蔗理苦10 小时前
2024-12-24 NO1. XR Interaction ToolKit 环境配置
unity·quest3·xr toolkit
花生糖@10 小时前
Android XR 应用程序开发 | 从 Unity 6 开发准备到应用程序构建的步骤
android·unity·xr·android xr
向宇it11 小时前
【从零开始入门unity游戏开发之——unity篇02】unity6基础入门——软件下载安装、Unity Hub配置、安装unity编辑器、许可证管理
开发语言·unity·c#·编辑器·游戏引擎
虾球xz11 小时前
游戏引擎学习第55天
学习·游戏引擎
yngsqq11 小时前
一键打断线(根据相交点打断)——CAD c# 二次开发
windows·microsoft·c#