简体   繁体   中英

C# Code Injection?

So I have a bunch of functions that I use OVER AND OVER again all over the place in random areas. And also some getters and setters.

For example just stuff like this:

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;

This is for Unity if you can't tell.

What I would really like to do is take those functions and put them somewhere else. Then in my classes just do like

[TransformCache]

Some kind of one line tag and it would place the function, from elsewhere, inline into my class.

I know there is some complex way to do this with Mono.Cecil, which if anyone has a simple tutorial on that I'd love the link.

But is there an easier way than that? I know C and Objective-C, and even CG code have functions to do this. Is there anyway to do this in C# with ease?

I don't know if this will help you or not, but how about wrapping some of these common things you want into a wrapper class, then just add the class to your other game object. Something like

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;
}

Then, in your classes that you will be using it

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;
   }   
}

Sorry... in C++ you can derive from multiple classes which in essence COULD allow something like that. The only other thing I can think of is looking into using Generics if your functions use repeated similar types via GetComponent() calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM