Unity3D读取XML数据

本文介绍如何在Unity中创建并加载XML配置文件。通过在StreamingAssets文件夹下放置XML文件,然后使用C#代码读取,具体展示了如何在代码中获取XML文件中的ServerIP信息。

还是在这里做个笔记,不然容易记不住……

1.首先先在Asses下创建StreamingAssets文件夹、然后将配置文件、也就是要读取的xml文件放到该文件夹下

2.然后就可以开始写代码啦(我是为了方便调用、在这里顺便写了个单例)

using UnityEngine;
using System.Xml;
public class Xml : MonoBehaviour
{
    public static Xml instance;
    public string ServerIP;
    // Start is called before the first frame update
    
    void Start()
    {
        LoadXml();
    }
    void Awake()
    {
        instance = this;
    }
    private void LoadXml(){
        
        XmlDocument xml = new XmlDocument();
        //---------------config.xml是文件的名字
        xml.Load(Application.dataPath + "/StreamingAssets/config.xml");
        //---------------这里WebSocketConfig是一个标签
        XmlNodeList xmlNodeList = xml.SelectSingleNode("WebSocketConfig").ChildNodes;
        foreach (XmlElement xl1 in xmlNodeList)
        {
            ServerIP = xmlNodeList.Item(0).InnerText;
        }  
    }

// Update is called once per frame
void Update()
    {
        
    }
}

这个是我的xml文件示例,对应着需要用到的xml进行套用就行

3.最后在Unity场景中、将代码挂载就可以用了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值