unity中 字串與類中GameObject變數的相互引用
阿新 • • 發佈:2019-02-15
一、字串引用GameObject變數
using UnityEngine; using System; using System.Linq.Expressions; public class Test : MonoBehaviour { public GameObject camerrr; void Start() { GameObject go = this.GetType().GetField("camerrr").GetValue(this) as GameObject; Debug.Log(go.transform.position); //此時的go即為inspector面板中賦值的GameObject } }
二、通過GameObject變數得到其對應字串
三、聯網時,通過客戶端1傳過來的字串,獲得客戶端2中該字串對應GameObject的引用:public class Test : MonoBehaviour { public GameObject camerrr; void Start() { string propertyName = PropertySupport.ExtractPropertyName(() => this.camerrr); Debug.Log(propertyName);//輸出 camerrr } //獲取變數字串方法 public static class PropertySupport { public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression) { MemberExpression memberExpression = propertyExpression.Body as MemberExpression; return memberExpression.Member.Name; } } }
using UnityEngine; using System; using System.Linq.Expressions; public class Test : MonoBehaviour { public GameObject camerrr; void Start () { string propertyName = PropertySupport.ExtractPropertyName(() => this.camerrr); GameObject go = this.GetType().GetField(propertyName).GetValue(this) as GameObject; Debug.Log(go.transform.position); } //獲取方法 public static class PropertySupport { public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression) { MemberExpression memberExpression = propertyExpression.Body as MemberExpression; return memberExpression.Member.Name; } } }