using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
public class ResourcesUpdate : MonoBehaviour
{
private static ResourcesUpdate instance;
public static ResourcesUpdate GetInstance ()
{
return instance;
}
//本地存储版本号,在第一次装包时使用,以后都和persistent目录下的版本号对比
public static readonly string LOCAL_VERSION_FILE = "/LocalVersion.txt";
//本地URL下载地址,在assestStream目录下
public static string LOCAL_RES_URL = "";
#region 服务器版本号、资源bundle、Codebundle
//服务器URL下载地址
public static string SERVER_RES_URL = "http://192.168.1.248:80/ymres/android/";
//服务器上的版本文件
public static string SERVER_VERSION_FILE = "/ServerVersion.txt";
//服务器上资源文件夹名字
public static string SERVER_ALl_PREFAB = "/ServerResources/ALL.assetbundle";
//服务器上Code dll名字
public static string SERVER_CODE_DLL = "/CoinRunner_dll.assetbundle";
//服务器上XML配置
public static string SERVER_XMLCONFIG = "/xmlConfig.zip";
#endregion
#region 本地persistent版本号、资源bundle、Codebundle
//服务器下载下来保存到本地永久目录的版本号文件名
public static readonly string LOCAL_PERSISTENT_VERSION_FILE = "/LOCAL_Version.txt";
//服务器下载下来保存到本地的Code dll 名字
public static readonly string LOCAL_CODE_PERSISTENT_DLL = "/CoinRunner_dll.assetbundle";
//服务器下载下来保存到本地的资源 dll 名字
public static readonly string LOCAL_ALl_PERSISTENT_PREFAB = "/LOCAL_ALL.assetbundle";
//本地资源永久路径,保存手机persistent
public static string LOCAL_RES_PERSISTENT_PATH = "";
//本地Code永久路径,保存手机persistent
public static string LOCAL_CODE_PERSISTENT_PATH = "";
#endregion
private string codeDllName = "CoinRunner_dll";
private List<string> LocalResVersion;
private List<string> ServerResVersion;
public delegate void HandleFinishDownload (WWW www);
public delegate void DownloadFinishResources ();
public DownloadFinishResources finishResources;
public DownloadFinishResources finishCode;
public AssetBundle bundle;
private bool isNeedUpdateRes = false;
private bool isNeedUpdateCode = false;
#region 本地和服务器版本号对比
private int localCodeVersion;
private int serverCodeVersion;
private int localPlatformType;
private int localResVersion;
private int serverResVersion;
private int serverPlatformType;
#endregion
public bool isLoadingResources = false;
public bool isLoadingCode = false;
public bool isServer = false;
public GameObject child;
public GameObject root;
private string platformPath = "";
private string platformValidateNumber = "";
void Awake ()
{
instance = this;
isServer = false;
CheckNetWorkType ();
InitURLPath ();
}
/// <summary>
/// 等到资源、代码加载完毕之后,再调用该方法
/// </summary>
void OpenGameObject(){
child.SetActive (true);
root.SetActive (true);
}
void CheckNetWorkType(){
switch (CheckNetWork ()) {
case 1://运行商网络
// CommonMesgTips.GetInstance ().ShowTipsMsg ("正在使用运行商流量...");
break;
case 2://Wifi
// CommonMesgTips.GetInstance ().ShowTipsMsg ("Wifi");
// GLogger.LogError ("233333333333333333WifiWifiWifiWifiWifiWifiWifiWifi33333333333333333333333333");
break;
case -1://无网络连接
CommonMesgTips.GetInstance ().ShowTipsMsg ("网络未连接,请检查网络!");
break;
default:
break;
}
}
/// <summary>
/// //NotReachable 网络不可达
//ReachableViaCarrierDataNetwork 网络通过运营商数据网络是可达的。
//ReachableViaLocalAreaNetwork 网络通过WiFi或有线网络是可达的。
/// </summary>
/// <returns>The net work.</returns>
public int CheckNetWork ()
{
if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork) {
return 1;
} else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork) {
return 2;
} else {
return -1;
}
}
/// <summary>
/// 1、得到本地持久化目录路径
/// 2、得到本地StreamingAsset目录
/// 3、初始化服务器下载路径
/// </summary>
void InitURLPath (){
//保存到本地持久化目录
LOCAL_RES_PERSISTENT_PATH = GameUtils.GetDocumentsPath ();// + "/"
LOCAL_CODE_PERSISTENT_PATH = GameUtils.GetDocumentsPath ();
LOCAL_RES_URL = GameUtils.GetStreamingAssetsPath ();
//PlatformConfig
// platformPath = "http://xian.ruanko.com/ymres/android/PlatformType.txt";
platformPath = GameUtils.GetStreamingAssetsPath () + "/PlatformConfig.txt";
platformValidateNumber = GameUtils.GetStreamingAssetsPath () + "/PayValidateConfig.txt";
if (isServer) {
GLogger.LogError (">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>从服务器下载...");
// SERVER_RES_URL = "http://192.168.1.248:80/ymres/android/";
SERVER_RES_URL = "http://xian.ruanko.com/ymres/android/";
SERVER_VERSION_FILE = "/ServerVersion.txt";
//服务器上资源文件夹名字
SERVER_ALl_PREFAB = "/ALL.assetbundle";
//服务器上Code dll名字
SERVER_CODE_DLL = "/CoinRunner_dll.assetbundle";
SERVER_XMLCONFIG = "/xmlConfig.zip";
} else {
SERVER_RES_URL = GameUtils.GetStreamingAssetsPath ();
SERVER_VERSION_FILE = "/ServerVersion.txt";
//服务器上资源文件夹名字
SERVER_ALl_PREFAB = "/ServerResources/ALL.assetbundle";
//服务器上Code dll名字
SERVER_CODE_DLL = "/CoinRunner_dll.assetbundle";
SERVER_XMLCONFIG = "/xmlConfig.zip";
}
}
void Start ()
{
LocalResVersion = new List<string> ();
ServerResVersion = new List<string> ();
if (bundle != null) {
return;
} else {
LoadLocalVersion ();
}
}
public void LoadLocalVersion ()
{
StartCoroutine (DownLoad (platformPath, delegate(WWW platformContent) {
ParsePlatformType(platformContent.text);
}));
StartCoroutine (DownLoad (platformValidateNumber, delegate(WWW PayValidateConfig) {
ParsePlatformValidate(PayValidateConfig.text);
}));
//加载本地version配置 SERVER_VERSION_FILE
StartCoroutine (DownLoad (GetLocalVersionFile (), delegate(WWW localVersion) {
//保存本地的version
ParseLocalVersionFile (localVersion.text);
//加载服务端version配置
StartCoroutine (this.DownLoad (SERVER_RES_URL + SERVER_VERSION_FILE, delegate(WWW serverVersion) {
//保存服务端version
ParseServerVersionFile (serverVersion.text);
CamparePlatformType();
//是否需要重新加载资源
CompareResVersion ();
//是否需要重新加载Code
CampareCodeVersion();
}));
}));
}
void ParsePlatformType(string _content){
int platformType = int.Parse(_content);
PlatformUserInfos.GetInstance ().currentPlatformType = platformType;
// int isChange = int.Parse(_content);
// PlatformUserInfos.GetInstance ().validateChinaMobile = isChange;
// GLogger.LogError (">>>>>>>>>>>>>isChange " + isChange);
// GLogger.LogError (">>>>>>>>>>>>>PlatformUserInfos.GetInstance ().isTest " + PlatformUserInfos.GetInstance ().isTest);
}
void ParsePlatformValidate(string _content){
int platformValidateType = int.Parse(_content);
// PlatformUserInfos.GetInstance ().currentPlatformType = platformValidateType;
if (platformValidateType == 1) {
PlatformUserInfos.GetInstance ().validateNumber = PlatformPayValidateStatus.FormalValidate;
} else if (platformValidateType == 2) {
PlatformUserInfos.GetInstance ().validateNumber = PlatformPayValidateStatus.TestValidate;
} else if (platformValidateType == 3) {
PlatformUserInfos.GetInstance ().validateNumber = PlatformPayValidateStatus.DevelopValidate;
}
GLogger.LogError (">>>>>>>>>>>>>>>>PlatformUserInfos.GetInstance ().validateNumber " + (int)PlatformUserInfos.GetInstance ().validateNumber);
}
string GetLocalVersionFile ()
{
string filePath = null;
if (File.Exists (LOCAL_RES_PERSISTENT_PATH.Replace("file://", "") + LOCAL_PERSISTENT_VERSION_FILE)) {
filePath = LOCAL_RES_PERSISTENT_PATH + LOCAL_PERSISTENT_VERSION_FILE;
} else {
filePath = LOCAL_RES_URL + LOCAL_VERSION_FILE;
}
return filePath;
}
/// <summary>
/// 读取streamingAssetsPath下的Version文件到PersistentDataPath下
/// </summary>
void SaveVersionToPersistentDataPath (string localVersion)
{
FileStream stream;
string filePath = LOCAL_RES_PERSISTENT_PATH.Replace ("file://", "") + LOCAL_PERSISTENT_VERSION_FILE;
if (File.Exists (filePath)) {
stream = new FileStream (filePath, FileMode.Create);
} else {
CreateDic (filePath);
stream = File.Create (filePath);
}
byte[] data = Encoding.UTF8.GetBytes (localVersion);
stream.Write (data, 0, data.Length);
stream.Flush ();
stream.Close ();
}
private IEnumerator DownLoad (string url, HandleFinishDownload finishFun)
{
WWW www = new WWW (url);
yield return www;
if (www.isDone) {
if (finishFun != null) {
finishFun (www);
}
}
www.Dispose ();
}
private void ParseLocalVersionFile (string content)
{
if (content == null || content.Length == 0) {
return;
}
string[] items = content.Split (new char[] { '\n' });
foreach (string item in items) {
LocalResVersion.Add (item);
}
ParseVersion.GetInstance ().LoadVersion (content);
localResVersion = ParseVersion.GetInstance ().GetResVersionNum ();
localCodeVersion = ParseVersion.GetInstance ().GetCodeVersionNum ();
localPlatformType = ParseVersion.GetInstance ().GetPlatformType ();
// PlatformUserInfos.GetInstance().currentPlatformType = ParseVersion.GetInstance ().GetPlatformType ();
}
private void ParseServerVersionFile (string content)
{
if (content == null || content.Length == 0) {
return;
}
string[] items = content.Split (new char[] { '\n' });
foreach (string item in items) {
ServerResVersion.Add (item);
}
ParseVersion.GetInstance ().LoadVersion (content);
serverResVersion = ParseVersion.GetInstance ().GetResVersionNum ();
serverCodeVersion = ParseVersion.GetInstance ().GetCodeVersionNum ();
serverPlatformType = ParseVersion.GetInstance ().GetPlatformType ();
PlatformUserInfos.GetInstance().validateChinaMobile = ParseVersion.GetInstance ().GetPlatformType ();
}
private void CompareResVersion ()
{
if (localResVersion != serverResVersion) {
GLogger.LogWarning (">>>>>>>>>>>>>>资源版本不相等!!!");
isNeedUpdateRes = true;
//加载需要更新的资源
DownLoadRes ();
} else {
isNeedUpdateRes = false;
GLogger.LogWarning (">>>>>>>资源版本相等!!!");
DownLoadRes ();
}
}
private void CampareCodeVersion(){
if (localCodeVersion != serverCodeVersion) {
GLogger.LogWarning (">>>>>>>>>>>>>>代码版本不相等!!!" + " localCodeVersion: " + localCodeVersion + " serverCodeVersion: " + serverCodeVersion);
isNeedUpdateCode = true;
DownLoadCode ();
} else {
GLogger.LogWarning (">>>>>>>>代码版本相等!!!");
isNeedUpdateCode = false;
DownLoadCode ();
}
}
private void CamparePlatformType(){
GLogger.LogError (">>>> 当前SDK ID >>>>>>:" + PlatformUserInfos.GetInstance ().currentPlatformType);
}
//依次加载需要更新的资源
private void DownLoadRes ()
{
if (!isNeedUpdateRes) {
//加载XML
LoadAndShowAssetBundle ();
return;
} else {
// if(isServer){
LoadXML ();
// }
}
UpdateLocalVersionFile ();
StartCoroutine (this.DownLoad (SERVER_RES_URL + SERVER_ALl_PREFAB, delegate(WWW w) {
//将下载的资源替换本地旧的资源
ReplaceLocalRes (LOCAL_ALl_PERSISTENT_PREFAB, w.bytes);
isNeedUpdateRes = false;
DownLoadRes ();
}));
}
void LoadXML(){
string inputPath = null;
if (isServer) {
inputPath = SERVER_RES_URL + SERVER_XMLCONFIG;
} else {
inputPath = GameUtils.GetAssetPath () + "/xmlConfig.zip";
}
StartCoroutine (DownLoad(inputPath,DecompressXMLConfig));
}
void DecompressXMLConfig(WWW www){
string inputPath = GameUtils.GetDocumentsPath ().Replace ("file://","")+"/xmlConfig.zip";
GLogger.LogError (">>>>>>>>>>>>>>>>>加载XML资源>>>>>>>>>>>>>>>>");
FileStream stream;
if (File.Exists (inputPath)) {
stream = new FileStream (inputPath, FileMode.Create);
} else {
CreateDic (inputPath);
stream = File.Create (inputPath);
}
byte[] data = www.bytes;
stream.Write (data, 0, data.Length);
stream.Flush ();
stream.Close ();
string outputPath = GameUtils.GetDocumentsPath ().Replace ("file://","")+"/Config/";
if(Directory.Exists(outputPath)){
Directory.Delete (outputPath,true);
}
DecompressTool.DecompressFiles7Zip(inputPath, outputPath);
}
void LoadAndShowAssetBundle ()
{
isLoadingResources = true;
GLogger.LogWarning ("正在加载资源...");
string filePath = null;
if (File.Exists (LOCAL_RES_PERSISTENT_PATH.Replace ("file://", "") + LOCAL_ALl_PERSISTENT_PREFAB)) {
filePath = string.Format ("{0}{1}", LOCAL_RES_PERSISTENT_PATH, LOCAL_ALl_PERSISTENT_PREFAB);
} else {
GLogger.LogWarning ("************************本地加载资源不存在************************");
}
StartCoroutine (this.DownLoad (filePath, DownLoadFinishRes));
}
void DownLoadFinishRes(WWW www){
bundle = www.assetBundle;
isLoadingResources = false;
if (finishResources != null) {
finishResources ();
}
}
private void DownLoadCode (){
if (!isNeedUpdateCode) {
LoadCodeAssembly ();
return;
}
UpdateLocalVersionFile ();
StartCoroutine (this.DownLoad (SERVER_RES_URL + SERVER_CODE_DLL, delegate(WWW w) {
//将下载的资源替换本地旧的资源
ReplaceLocalRes (LOCAL_CODE_PERSISTENT_DLL, w.bytes);
isNeedUpdateCode = false;
DownLoadCode ();
}));
}
private void LoadCodeAssembly(){
isLoadingCode = true;
GLogger.LogWarning ("正在加载代码...");
string filePath = null;
if (File.Exists (LOCAL_CODE_PERSISTENT_PATH.Replace ("file://", "") + LOCAL_CODE_PERSISTENT_DLL)) {
filePath = string.Format ("{0}{1}", LOCAL_CODE_PERSISTENT_PATH, LOCAL_CODE_PERSISTENT_DLL);
} else {
GLogger.LogWarning ("************************本地加载Code不存在************************");
}
StartCoroutine (this.DownLoad (filePath, DownloadFinishCode));
}
void DownloadFinishCode(WWW www){
AssetBundle bundle = www.assetBundle;
TextAsset assets = bundle.Load (codeDllName, typeof(TextAsset)) as TextAsset;
LocalResourceManager.assembly = Assembly.Load (assets.bytes);
isLoadingCode = false;
LocalResourceManager.GetInstance ().LoadCodeDll ();
OpenGameObject ();
if (finishCode != null) {
finishCode ();
}
}
//更新本地的version配置
private void UpdateLocalVersionFile ()
{
if (isNeedUpdateRes || isNeedUpdateCode) {
StringBuilder versions = new StringBuilder ();
foreach (var item in ServerResVersion) {
versions.Append (item).Append ("\n");
}
UpdatePersistentVersionFile (versions);
}
}
void UpdatePersistentVersionFile (StringBuilder versions)
{
string filePersistentPath = string.Format ("{0}{1}",LOCAL_RES_PERSISTENT_PATH.Replace ("file://", ""),LOCAL_PERSISTENT_VERSION_FILE);
UpdateVersionFile (filePersistentPath, versions);
}
void UpdateVersionFile (string filePath, StringBuilder versions)
{
GLogger.LogWarning ("====================更新LocalVersion! " + filePath);
FileStream stream;
if (File.Exists (filePath)) {
stream = new FileStream (filePath, FileMode.Create);
} else {
CreateDic (filePath);
stream = File.Create (filePath);
}
byte[] data = Encoding.UTF8.GetBytes (versions.ToString ());
stream.Write (data, 0, data.Length);
stream.Flush ();
stream.Close ();
}
private void ReplaceLocalRes (string fileName, byte[] data)
{
FileStream stream;
string filePath = LOCAL_RES_PERSISTENT_PATH.Replace ("file://", "") + fileName;
if (File.Exists (filePath)) {
stream = new FileStream (filePath, FileMode.Create);
} else {
CreateDic (filePath);
stream = File.Create (filePath);
}
stream.Write (data, 0, data.Length);
stream.Flush ();
stream.Close ();
}
//创建路径
void CreateDic (string filePath)
{
int index = filePath.LastIndexOf ('/');
string dir = filePath.Substring (0, index + 1);
if (!Directory.Exists (dir)) {
Directory.CreateDirectory (dir);
}
}
}
/// <summary>
/// 保存本地资源dll到持久化目录
/// </summary>
/// <param name="prefabDll">Prefab dll.</param>
// void SavePrefabDllToPersistentDataPath (string prefabDll)
// {
// FileStream stream;
// string filePath = LOCAL_RES_PERSISTENT_PATH.Replace ("file://", "") + LOCAL_ALl_PERSISTENT_PREFAB;
// if (File.Exists (filePath)) {
// stream = new FileStream (filePath, FileMode.Create);
// } else {
// CreateDic (filePath);
// stream = File.Create (filePath);
// }
// byte[] data = Encoding.UTF8.GetBytes (prefabDll);
// stream.Write (data, 0, data.Length);
// stream.Flush ();
// stream.Close ();
// }
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
public class LocalResourceManager : MonoBehaviour
{
public static Assembly assembly;
private static LocalResourceManager instance;
public GameObject Child;
public GameObject Root;
public GameObject parseBaseXml;
public delegate void HandleFinishDownloads (WWW www);
public static LocalResourceManager GetInstance ()
{
return instance;
}
void Awake ()
{
instance = this;
}
public void LoadCodeDll(){
if (assembly != null) {
parseBaseXml.SetActive (true);
return;
}
}
void Start(){
DontDestroyOnLoad (gameObject);
}
//给物体上挂在脚本
public void AddComponentToResource (string className, GameObject gb)
{
System.Type type = assembly.GetType (className);
// GLogger.LogWarning ("--------------类名:" + type);
if (type == null) {
GLogger.LogWarning ("null--------------");
}
if (gb == null) {
GLogger.LogWarning ("null-------物体为空-------");
}
// GLogger.Log (type + "***********************************" + className);
if (gb != null && type != null && gb.GetComponent (type) == null) {
gb.AddComponent (type);
}
}
}
using System;
using UnityEngine;
public class GetCommponent : MonoBehaviour
{
//物体上添加的脚本
public string[] className;
// public BaseView baseView;
//物体上默认属性的值
public int[] defaultIntVale;
//物体上默认属性的值
public float[] defaultFloatVale;
//物体上默认属性的值
public string[] defaultStrVal;
public bool[] defaultBool;
//物体上默认属性的值
public GameObject[] defaultGameObject;
void Awake(){
if (className == null || className.Length <= 0) {
return;
}
// Debug.Log("add");
for (int i = 0; i < className.Length; i++) {
// GLogger.LogWarning("00000000000000 " + className[i]);
LocalResourceManager.GetInstance ().AddComponentToResource (className[i], gameObject);
}
}
public T GetDefaultGB<T>(int index){
if (defaultGameObject == null || defaultGameObject.Length <= 0) {
GLogger.Log ("get gameobject fail: the defaultGameObject is null");
return default(T);
}
if (index < 0 || index >= defaultGameObject.Length) {
GLogger.Log ("get gameobject fail: IndexOutOfRangeException index error " + index);
return default(T);
}
if (defaultGameObject [index] == null) {
GLogger.Log ("get gameobject fail: the index gameobject is null " + index);
return default(T);
}
Type type = typeof(T);
// Debug.Log(type);
if (type.Name == "GameObject") {
return (T)Convert.ChangeType(defaultGameObject[index],type);
}
return (T)Convert.ChangeType(defaultGameObject[index].GetComponent(type),type);
}
}
资源更新
最新推荐文章于 2020-11-12 14:22:03 发布