using System; using UnityEngine; using Object = UnityEngine.Object; namespace XGame.Framework.Asset { internal static class Extensions { /// /// object转泛型对象的扩展 /// /// /// /// 用于转换错误时将名字打印出来 /// public static TResult Convert(this object value, string addressableName) { if (value != null) { Type type = typeof(TResult); if (type.IsInstanceOfType(value)) { return (TResult)value; } if (type.IsClass) { if (type.IsSubclassOf(typeof(Component))) { var go = value as GameObject; if (go != null) { return go.GetComponent(); } var component = value as Component; if (component != null) { return component.gameObject.GetComponent(); } } else if (type == typeof(Sprite) && value is Texture2D texture) { object sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); return (TResult) sprite; } } try { TResult result = (TResult)value; return result; } catch (Exception ex) { AssetsLog.Error($"object conver type Error. source type:{value.GetType()} name:{value} target:{type} addressable:{addressableName}"); AssetsLog.Exception(ex); } } return default; } /// /// 返回object的long格式的hashCode /// UnityEngine.Object返回的是instanceId << 32 /// /// /// public static long GetLongHashCode(this object obj) { if (obj == null) return 0; if (obj is Object uniObj) { long instanceId = uniObj.GetInstanceID(); instanceId <<= 32; return instanceId; } return obj.GetHashCode(); } /// /// 释放Object对象 /// 独立资源才能使用Resources.UnloadAsset /// /// /// public static bool Unload(this Object asset) { if (asset == null || asset is Component || asset is GameObject || asset is AssetBundle) { //非独立资源 } else { //独立资源才能使用Resources.UnloadAsset Resources.UnloadAsset(asset); return true; } return false; } //public static string SaveToLower(this string msg) //{ // if (string.IsNullOrEmpty(msg)) // { // return msg; // } // return msg.ToLower(); //} } }