Search code examples
c#genericsluaxnanlua

Syntax to call generic C# method from NLua


I'm having some trouble figuring out the correct syntax for calling a generic C# function from Lua with NLua.

I'm trying to call the following C# XNA function from Lua

GameWorld.Instance.Content.Load<Texture2D>("player");

But I'm having some syntax trouble with the generic <T> part. My current lua call looks like this, which is clearly not correct, since I'm getting a LuaScriptException.

GameWorld.Instance.Content:Load<Texture2D>("player")

Solution

  • I'm create class AssetManager with pair of Load/Get methods for each asset type.

    class AssetManager
    {
        private ContentManager content;
        private Dictionary<string, Texture2D> textures; // fonts, sprites, models and so on
    
        AssetManager(ContentManager  pContent)
        {
            this.content = pContent;
            this.textures = new Dictionary<string, Texture2D>();
        }
    
        public void LoadTexture(string pName, string pAssetName)
        {
            this.textures.Add(pName, this.content.Load<Texture2D>(pAssetName);
        }
        public Texture2D GetTexture(stirng pName)
        {
            return this.Textures.ContainsKey(pName) ? this.Textures[pName] : null;
        }
    }
    

    Simple usage from both C# and Lua.