所以我有一堆函数,在随机区域里,我一遍又一遍地使用。还有一些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;如果你说不出来的话,这是给团结的。
我真正想做的是把这些功能放在其他地方。在我的课堂上,就像
[TransformCache]某种类型的一行标记,它会将函数从其他地方内联到我的类中。
我知道用Mono.Cecil做这件事有一些复杂的方法,如果有人有一个简单的教程,我会很喜欢这个链接的。
但还有比这更简单的方法吗?我知道C和Objective,甚至CG代码也有这样的功能。在C#中是否可以轻松地做到这一点呢?
发布于 2014-12-22 04:26:47
我不知道这是否对你有帮助,但是把你想要的一些常见的东西包装到一个包装类中,然后把这个类添加到你的另一个游戏对象中怎么样?有点像
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()调用使用重复的类似类型,那么我唯一能想到的另一件事就是使用泛型。
https://stackoverflow.com/questions/27596311
复制相似问题