使用拓展方法設定和獲取Transfrom資訊
阿新 • • 發佈:2019-01-27
在專案開發中經常需要儲存場景中物體的旋轉,位置,大小。為了每次儲存成統一的格式方便複用,給Transfrom加入設定和獲取的拓展方法。關於拓展方法的可以推薦 拓展方法 這篇文章。下面是改功能的實現:
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 類必須是靜態類, /// 另外擴充套件方法(Extension Methods)必須也是靜態方法, /// 方法的引數中必須要有被擴充套件類作為其中一個引數, /// 此引數前面用this關鍵字修飾。 /// </summary> public static class TransformExtension { /// <summary> /// 根據字串設定Transform的位置旋轉和縮放 /// </summary> /// <param name="transform"></param> /// <param name="info">px,py,pz;rx,ry,rz;sx,sy,sz</param> public static void SetTransformByString(this Transform transform, string info) { string[] infos = info.Split(';'); if (infos.Length >= 3) { transform.localPosition = GetVectorFromString(infos[0]); transform.localEulerAngles = GetVectorFromString(infos[1]); transform.localScale = GetVectorFromString(infos[2]); } } /// <summary> /// 獲取transform 9軸資訊的字串 /// </summary> /// <param name="transform"></param> /// <returns>px,py,pz;rx,ry,rz;sx,sy,sz</returns> public static string GetTransformDetails(this Transform transform) { string result = ""; result += GetVectorString(transform.localPosition) + ";"; result += GetVectorString(transform.localEulerAngles) + ";"; result += GetVectorString(transform.localScale); return result; } public static Vector3 GetVectorFromString(string str) { Vector3 result = Vector3.zero; try { string[] temps = str.Split(','); result.x = float.Parse(temps[0]); result.y = float.Parse(temps[1]); result.z = float.Parse(temps[2]); } catch (Exception e) { throw e; } return result; } public static string GetVectorString(Vector3 vec) { string result = vec.x.ToString("0.00") + "," + vec.y.ToString("0.00") + "," + vec.z.ToString("0.00"); return result; } }