Valks-Games / Unity-Transport-Layer-UDP-Model

Learning the new Unity Transport Layer
MIT License
3 stars 0 forks source link

Loading Commands Dynamically #10

Closed valkyrienyanko closed 4 years ago

valkyrienyanko commented 4 years ago

Right now all commands are loaded manually. https://github.com/valkyrienyanko/Unity-Transport-Layer-Boilerplate/blob/2b0450020b623bd31b0f9852c84d6e652afe7432/Server/Assets/Scripts/Console.cs#L44-L52

If the commands were loaded dynamically somehow, this would save the time of having to manually type out each new command in the future. https://github.com/valkyrienyanko/Unity-Transport-Layer-Boilerplate/blob/2b0450020b623bd31b0f9852c84d6e652afe7432/Server/Assets/Scripts/Console.cs#L33-L42

valkyrienyanko commented 4 years ago

Can't be solved without ugly reflection.

valkyrienyanko commented 4 years ago
Commands = typeof(Command) // Gets the type Command
    .Assembly // Gets the assembly (.DLL) where Command is located
    .GetTypes() // Gets all the types of the assembly where Command is located
    .Where(x => typeof(Command).IsAssignableFrom(x) && // Filters by types that inherits Command
    !x.IsAbstract) // Excluding abstract types
    .Select(Activator.CreateInstance) // Creates an instance of each one
    .Cast<Command>() // Cast them all to Command
    .ToDictionary(x => x.GetType().Name.ToLower(), x => x); // creates the dictionary