[英]C# Code Injection?
所以我有一堆函數,我在隨機區域的地方再次使用OVER AND OVER。 還有一些吸氣劑和二傳手。
例如,像這樣的東西:
public GameObject GameObjectCache
{
get
{
if (gameObjectCache == null)
gameObjectCache = this.gameObject;
return gameObjectCache;
}
}
private GameObject gameObjectCache;
public Transform TransformCache
{
get
{
if (transformCache == null)
transformCache = this.GetComponent<Transform>();
return transformCache;
}
}
private Transform transformCache;
如果您無法分辨,這適用於Unity。
我真正想做的是把這些功能放到其他地方。 然后在我的課堂上就好了
[TransformCache]
某種單行標記,它會將函數從其他地方內聯到我的類中。
我知道有一些復雜的方法可以使用Mono.Cecil,如果有人有一個簡單的教程我喜歡這個鏈接。
但有比這更簡單的方法嗎? 我知道C和Objective-C,甚至CG代碼都有這樣的功能。 無論如何在C#中輕松做到這一點?
我不知道這是否會對你有所幫助,但如何將你想要的一些常見內容包裝到包裝類中,然后將類添加到其他游戲對象中。 就像是
public class MyWrapper
{
private GameObject parentGameObj;
public MyWrapper(GameObject srcObj)
{
parentGameObj = srcObj;
}
public GameObject GameObjectCache
{
get
{
if (gameObjectCache == null)
gameObjectCache = parentGameObj.gameObject;
return gameObjectCache;
}
}
private GameObject gameObjectCache;
public Transform TransformCache
{
get
{
if (transformCache == null)
transformCache = parentGameObj.GetComponent<Transform>();
return transformCache;
}
}
private Transform transformCache;
}
然后,在您將要使用它的課程中
public class YourOtherClass : GameObject
{
MyWrapper mywrapper;
public Start()
{
// instantiate the wrapper object with the game object as the basis
myWrapper = new MyWrapper(this);
// then you can get the game and transform cache objects via
GameObject cache1 = myWrapper.GameObjectCache;
Transform tcache1 = myWrapper.TransformCache;
}
}
抱歉...在C ++中,您可以從多個類派生,這些類實際上可以允許類似的東西。 我能想到的另一件事就是如果你的函數通過GetComponent()調用使用重復的類似類型,那么就要考慮使用泛型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.