首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#代码注入?

C#代码注入?
EN

Stack Overflow用户
提问于 2014-12-22 03:43:12
回答 1查看 1.7K关注 0票数 3

所以我有一堆函数,在随机区域里,我一遍又一遍地使用。还有一些getter和setter。

例如,就像这样的东西:

代码语言:javascript
运行
复制
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;

如果你说不出来的话,这是给团结的。

我真正想做的是把这些功能放在其他地方。在我的课堂上,就像

代码语言:javascript
运行
复制
[TransformCache]

某种类型的一行标记,它会将函数从其他地方内联到我的类中。

我知道用Mono.Cecil做这件事有一些复杂的方法,如果有人有一个简单的教程,我会很喜欢这个链接的。

但还有比这更简单的方法吗?我知道C和Objective,甚至CG代码也有这样的功能。在C#中是否可以轻松地做到这一点呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-22 04:26:47

我不知道这是否对你有帮助,但是把你想要的一些常见的东西包装到一个包装类中,然后把这个类添加到你的另一个游戏对象中怎么样?有点像

代码语言:javascript
运行
复制
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;
}

然后,在您的类中,您将使用它

代码语言:javascript
运行
复制
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()调用使用重复的类似类型,那么我唯一能想到的另一件事就是使用泛型。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27596311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档