场景下载相关(简单展示)

场景资源下载,将一个下载管理在启动的时候就挂载到DonDestroy物体上面,然后就可以随时调用下载功能。

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

//参数 当前下载进度,ab包的资源名字,错误信息(如果为空则没有报错)
public delegate void BundleDownloadProgress(float percent, string sceneName = “”, string errorInfo = “”);

//下载完成回调
public delegate void BundleDownloadComplete(string sceneName);

//下载过程突然断网回调
public delegate void NotNetBundleDownload(string sceneName = “”);

public class TaskInfo
{
public string TaskName;
public UnityWebRequest Request;
}

public class BundleLoader : MonoBehaviour
{
public BundleDownloadProgress onBundleDownloadProgress;

public BundleDownloadComplete onBundleDownloadComplete;

public NotNetBundleDownload onNotNetBundleDownload;

private List<TaskInfo> m_taskList = new List<TaskInfo>();

private static BundleLoader m_instance;
public static BundleLoader Instance
{
    get
    {
        return m_instance;
    }
}

public bool IsRemoveTask=false;//true 为清空
private void Awake()
{
    m_instance = this;
}

private void Update()
{
    for (int i = 0; i < m_taskList.Count; ++i)
    {
        TaskInfo info = m_taskList[i];
        if (IsRemoveTask)
        {
            if (!m_taskList[i].TaskName.Equals("pipihome_texture"))
            {
                m_taskList.Remove(info);
                --i;
                if ((m_taskList.Count <= 0) || (m_taskList[0].TaskName.Equals("pipihome_texture") && m_taskList.Count <= 1))
                {
                    IsRemoveTask = false;
                }
                continue;
            }
        }
        if (!NetPostManager.Instance.IsHaveNet())
        {
            if (onNotNetBundleDownload != null)
            {
                m_taskList.Clear();
                //LogSystem.Log("onNotNetBundleDownload....", LogColor.yellow);
                onNotNetBundleDownload(info.TaskName);
                return;
            }
        }
        if (onBundleDownloadProgress != null)
        {
            //LogSystem.Log(".....onBundleDownloadProgress...."+ info.Request.error, LogColor.yellow);
            if (!string.IsNullOrEmpty(info.Request.error))
            {
                m_taskList.Remove(info);
                --i;
            }
            onBundleDownloadProgress(info.Request.downloadProgress,info.TaskName,info.Request.error);
        }

        if (info.Request.downloadHandler.isDone)
        {
            if (string.IsNullOrEmpty(info.Request.error))
            {
                //下载成功
                DeleteFile(info.TaskName);
                WriteFile(info.TaskName, info.Request.downloadHandler.data, info.Request.downloadHandler.data.Length);

                SceneLoader.Instance.UpdateLocalXml(info.TaskName);
            }
            else
            {
                //下载失败
                LogSystem.LogError(info.TaskName + "download failed cause:" + info.Request.error);
            }

            m_taskList.Remove(info);
            --i;
        }
        else if(!string.IsNullOrEmpty(info.Request.error))
        {
            LogSystem.LogError("info.error: " + info.Request.error);
        }
    }
}

//删除原有文件
private void DeleteFile(string name)
{
    string path = ResourcesDefine.LocalBundleDefine + "/" + name;
    if (File.Exists(path))
    {
        File.Delete(path);
    }
}

//文件写入
private void WriteFile(string name, byte[] info, int length)
{
    Stream sw;
    FileInfo file = new FileInfo(ResourcesDefine.LocalBundleDefine + "/" + name);
    if (file.Exists)
    {
        return;
    }

    //如果此文件不存在则创建
    sw = file.Create();

    sw.Write(info, 0, length);
    //关闭流
    sw.Close();
    //销毁流
    sw.Dispose();
    //LogSystem.Log("...xia zai wan chegn ...>>>" + onBundleDownloadComplete == null ? "null" : "onBundleDownloadComplete", LogColor.yellow);
    if (onBundleDownloadComplete != null)
    {
        onBundleDownloadComplete(name);
    }
}


public void AddTask(string name)
{
    TaskInfo info = new TaskInfo();
    info.TaskName = name;
    string url = ResourcesDefine.ServerBundleDefine + name;

    info.Request = UnityWebRequest.Get(url + GameCommonManager.RandomTime());
    info.Request.disposeDownloadHandlerOnDispose = true;
    info.Request.SendWebRequest();

    m_taskList.Add(info);
}
void RemoveTask(string name)
{
   
}

}
/-------------------------------------------------------------------------------------/
以上代码是挂载DontDestroy物体上面的。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Xml;
using UnityEngine.Networking;
using System;
using LogPrint;

public class SceneLoader
{
//场景配置文件名
public const string SCENE_FILE = “scenefile”;
//每个场景的所需assetbundle个数
public const int SCENE_BUNDLE_COUNT = 2;

//本地资源配置表
private readonly string m_localXmlPath = Application.persistentDataPath + "/LoadAssets.xml";

//远程资源配置表
private readonly string m_serverPath = ResourcesDefine.ServerConfigDefine + "LoadAssets.xml";

//远程资源配置缓存字典
public Dictionary<string, string> m_serverAssetsDic = new Dictionary<string, string>();

private XmlDocument m_xml = new XmlDocument();

private static SceneLoader m_instance;
public static SceneLoader Instance
{
    get
    {
        if (m_instance == null)
        {
            m_instance = new SceneLoader();
        }

        return m_instance;
    }
}

//读取远程资源配置
public IEnumerator LoadServerAssetsConfig()
{
    UnityWebRequest request = UnityWebRequest.Get(m_serverPath + GameCommonManager.RandomTime());
    yield return request.SendWebRequest();

    if (request.downloadHandler.isDone)
    {
        LoadServerAssetsXml(request.downloadHandler.text);

        LoadSceneConfig();
    }
}

private void LoadServerAssetsXml(string text)
{
    XmlDocument xml = new XmlDocument();
    xml.LoadXml(text);

    XmlNode root = xml.SelectSingleNode("Object");
    foreach (XmlElement element in root.ChildNodes)
    {
        string name = element.GetAttribute("Name");
        string hash = element.GetAttribute("Hash");

        if (!m_serverAssetsDic.ContainsKey(name))
        {
            m_serverAssetsDic.Add(name, hash);
        }
    }
}

private void LoadSceneConfig()
{
    if (!Directory.Exists(ResourcesDefine.LocalBundleDefine)) Directory.CreateDirectory(ResourcesDefine.LocalBundleDefine);

    //创建或加载本地资源配置
    if (File.Exists(m_localXmlPath))
    {
        m_xml.Load(m_localXmlPath);
    }
    else
    {
        CreateLocalXml();
    }

    //启动游戏下载场景配置
    BundleLoader.Instance.AddTask(SCENE_FILE);
}

//进入场景前检测场景
public void StartEnter(SceneType type)
{
    string sceneName = type.ToString();
    LogSystem.Log("...当前下载场景的名字.sender.name.2..." + sceneName , LogColor.yellow);
    //本地资源配置存在,对比后下载
    DownLoadCompare(sceneName);
}

//比较HASH进行下载
private void DownLoadCompare(string sceneName)
{
    if (m_serverAssetsDic.Count<=0)
    {

    }
   // LogSystem.Log("...当前下载场景的名字.sender.name.3..." + sceneName, LogColor.yellow);
    XmlNode root = m_xml.SelectSingleNode("Object");

    int assetbundleCount = 0;

    Dictionary<string, string>.Enumerator it = m_serverAssetsDic.GetEnumerator();
    while (it.MoveNext())
    {
        string realName = MainHouseManager.Instance.GetRealSceneName(it.Current.Key).ToLower();
       // LogSystem.Log("...当前下载场景的名字.realName.name.4..." + realName+ " >>>"+ sceneName.ToLower(), LogColor.yellow);
        if (!realName.Equals(sceneName.ToLower()))
        {
            continue;
        }

        XmlElement element = IsContains(root, it.Current.Key);

        if (element == null)
        {
            if (realName.Contains("pipihome"))
            {
                UIManger.Instance.Show<DownloadPanel>();
            }

            //本地无此配置,下载
            BundleLoader.Instance.AddTask(it.Current.Key);

            continue;
        }
       // LogSystem.Log("...当前下载场景的名字.realName.name.5..." + realName, LogColor.yellow);
        //本地配置有记录,对比HASH
        string localHash = element.GetAttribute("Hash");
        string serverHash = it.Current.Value;

        if (localHash.Equals(serverHash))
        {
            //hash相同,不用下载
            assetbundleCount++;

            //皮皮之家
            if (realName.Contains("pipihome") && assetbundleCount == 1)
            {
                SceneLoadManager.Instance.LoadScene(SceneType.PipiHome);
                break;
            }

            //场景
            if (assetbundleCount == SCENE_BUNDLE_COUNT)
            {
                //场景所需bundle已存在本地,跳出检测,直接进入场景
                SceneLoadManager.Instance.LoadScene((SceneType)Enum.Parse(typeof(SceneType), sceneName));

                //行为数据采集
                ClientDataCollection.Instance.AddHandle(sceneName, "Scene_011");

                break;
            }

            continue;
        }

        if (realName.Contains("pipihome"))
        {
            UIManger.Instance.Show<DownloadPanel>();
        }

        //下载
        BundleLoader.Instance.AddTask(it.Current.Key);
    }
}

//比较HASH,true 完全一样,false 不一致
public bool CheckHash(string sceneName)
{
    if (NetPostManager.Instance.IsHaveNet() == false)
    {
        return true;
    }
    XmlNode root = m_xml.SelectSingleNode("Object");

    int assetbundleCount = 0;

    Dictionary<string, string>.Enumerator it = m_serverAssetsDic.GetEnumerator();
    while (it.MoveNext())
    {
        string realName = MainHouseManager.Instance.GetRealSceneName(it.Current.Key).ToLower();

        if (!realName.Equals(sceneName.ToLower()))
        {
            continue;
        }

        XmlElement element = IsContains(root, it.Current.Key);

        if (element == null)
        {
            //本地没有资源
            continue;
        }

        //本地配置有记录,对比HASH
        string localHash = element.GetAttribute("Hash");
        string serverHash = it.Current.Value;

        if (localHash.Equals(serverHash))
        {
            //hash相同
            assetbundleCount++;                                

            //场景的两个文件sound和prefab的哈希都一样,则场景没有更新
            if (assetbundleCount == SCENE_BUNDLE_COUNT)
            {                      
                //行为数据采集  没有网则不采集数据
                //ClientDataCollection.Instance.AddHandle(sceneName, "Scene_011");
                
                return true;
            }

            continue;
        }

        
    }

    return false;
}


private void CreateLocalXml()
{
    //创建xml根节点,最上层节点
    XmlElement root = m_xml.CreateElement("Object");
    m_xml.AppendChild(root);

    m_xml.Save(m_localXmlPath);
}

private XmlElement IsContains(XmlNode root, string name)
{
    foreach (XmlElement element in root.ChildNodes)
    {
        if (element.GetAttribute("Name").Equals(name))
        {
            return element;
        }
    }

    return null;
}

//下载完成后更新XML
public void UpdateLocalXml(string name)
{
    string serverHash = m_serverAssetsDic[name];

    XmlNode root = m_xml.SelectSingleNode("Object");

    foreach (XmlElement element in root.ChildNodes)
    {
        if (element.GetAttribute("Name").Equals(name))
        {
            element.SetAttribute("Hash", serverHash);
            m_xml.Save(m_localXmlPath);

            return;
        }
    }

    //创建用户子节点
    XmlElement property = m_xml.CreateElement("Property");

    property.SetAttribute("Name", name);
    property.SetAttribute("Hash", serverHash);

    root.AppendChild(property);

    m_xml.Save(m_localXmlPath);
}

}

/----------------------------------/
以上代码是场景加载时的应用案例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值