samedi 29 février 2020

Getting all methods with custom attribute in c# never finds a method

So I created this function to get all methods with the custom attribute ExecuteFromConsole

    [ExecuteFromConsole("test", "help")]
    static void Test(string[] args)
    {
        Debug.Log("Test Ran");
    }

    public void AddAttributeCommands()
    {
        //get all methods with the execute attribute
        var methods = AppDomain.CurrentDomain.GetAssemblies()
                               .SelectMany(x => x.GetTypes())
                               .Where(x => x.IsClass)
                               .SelectMany(x => x.GetMethods())
                               .Where(x => x.GetCustomAttributes(typeof(ExecuteFromConsoleAttribute), false).FirstOrDefault() != null);

        //adds them to commands
        foreach (var method in methods) 
        {
            Debug.Log("Found attribute");
            ExecuteFromConsoleAttribute attribute = (ExecuteFromConsoleAttribute)method.GetCustomAttributes(typeof(ExecuteFromConsoleAttribute), false).First();
            if(!method.IsStatic)
            {
                Debug.LogError("ExecuteFromConsoleAttribute must be used on static functions only");
                continue;
            }
            CommandFunc func = (CommandFunc)Delegate.CreateDelegate(typeof(CommandFunc), method);
            AddCommand(attribute.command, func, attribute.help);
        }
    }

Which worked just fine when I initially tested it but now it will never enter the foreach loop and Debug.log("found attribute") meaning its not finding the method that is clearly right above it with the attribute. AFAIK I didn't modify anything that should have affected this.

Does anybody have an insight on why its not working or if I'm going about it all wrong and there is a better way that I should have been doing instead?

The project is in unity if that affects anything





Aucun commentaire:

Enregistrer un commentaire