C# 代码注入
本文关键字:注入 代码 | 更新日期: 2023-09-27 18:34:50
所以我有一堆函数,我在随机区域一遍又一遍地使用。还有一些getter和setter。
例如,像这样的东西:
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(( 调用使用重复的相似类型。