Home > Back-end >  General Idea Of Component System. Too much casting? Union like structs? other methods?
General Idea Of Component System. Too much casting? Union like structs? other methods?

Time:10-24

I've been investigating the idea of a component based system. Imagine I have made them like so :

public class CObject
{
    public Component[] components;

    public T GetComponent<T>(string name = string.empty)
    {
        foreach(var c in components) if(c is T) if(name != string.empty || c.name == name) return c as T;
    }
}

and then we'll be able to get a component from a script like so :

// ... some code
DragonComponent dragonComponent = dragonObject.GetComponent<DragonComponent>();
// some code ...

but as you see it will require Boxing for each call... I could make it more efficient by making an static dictionary for previous calls, and if a similar call was given, I could make it just use the dictionary. but still, it's very messy and not very efficient...

and there's the union-like structure I've heard where the GetComponent could be implemented like so :

public class CObject
{
    private class CTypes {
        public DragonComponent[] dragonComponents;
        public CameraFocus[] cameraFocuses;
    }

    CTypes components;

        public T GetComponent<T>()
        {
              switch(T)
              {
                   case DragonComponent:    return components.dragonComponents[0];
                   case CameraFocus:        return components.cameraFocuses[0];
              }
        }
}

which is super performant but very hard to implement... I have no idea how to automate the process of creating new types in the union-like structure.

What's the best approach?

thanks :D

CodePudding user response:

It seems like you're trying to implement your own IoC framework. There are lots of Dependency Injection frameworks out there. Even built into ASP.NET Core.

If that's too overkill for you, there are many easier alternatives for your case though. First, you might think of a dictionary:

private static readonly Dictionary<Type, object> _components = new();

public T GetComponent<T>() => (T)_components[typeof(T)];

Or, even more performant, use a static generic class:

private class ComponentCache<T>
{
   public static T Component { get; set; }
}

public T GetComponent<T>() => ComponentCache<T>.Component;

Also, boxing applies only to value types. Either way though, believe me the performance hit is negligable for whatever little program you as a beginner are coding right now.

These are not complete examples, but I hope will give you some pointers.

  • Related