Search code examples
c++visual-studiogame-enginegame-development

How to automatically determine IDs for gameObject's?


I'm trying to make ECS (Entity-Component-System) in C++ right now.

Here is my GameObject class :

class GameObject
{
private:
    int ID
    /*gameobject name, tranform */
public:
    int GetID();
    
    template<class component>
    void AddComponent()
    {
        component::ComponentAdded(this->ID);
    }

    template<class component>
    component& GetComponent()
    {
        return component(); //todo :: think about how to access
    }

};

and here is Meshrenderer(one of my components) :

struct MeshRenderer
{
    MeshRenderer();

    static std::vector<Mesh> meshes;
    static std::vector<Material> materials;
    static std::unordered_map<int, std::pair< int , int>> renderables; // gameobjectID, <mesh, material>

    static void ComponentAdded(int gameObjectID);
    static void SetMesh(int gameObjectID, Mesh& mesh);
    static void SetMaterial(int gameObjectID, Material& material);
};

I'm trying to fix getcomponent :

scene->gameObjects[2]->GetComponent<MeshRenderer>().SetMesh(scene->gameObjects[2]->GetID(), object);

to :

scene->gameObjects[2]->GetComponent<MeshRenderer>().SetMesh(object);

but I don't know how to automatically give gameObject's ID when calling certain components function.

I would appreciate if you give me any advice.


Solution

  • In order to have a unique value for each instance of GameObject you can:

    • introduce a static counter (of instantiations, not of existing instances) to the class GameObject
    • uincrement it in the constructor of the class GameObject
    • use its current value, at the time of instaatiating a new object which inherits `GameObject, by assigning it to an instance member of the new object during its constructor

    The counter should count instantiations (i.e. not decrement in destructor) instead of existing instances (i.e. do decremetn in destructors). Because I assume that GameObjects might get destroyed and new ones instantiated afterwards. That could end up with newer ones having identical IDs, if older ones get destructed before.

    This does of course assume that the number of all instantiations in your program never overflows whatever type you are using. If that happens things get problematic. I hope you do not need that. If you do, I think I might go for a stack of recently deleted IDs, to be used for new instantiations. That however will probably suffer memory issues for the kind of numbers which can overflow a long long int.

    (In case the uniqueness suffices as "very likely not to ever be identical" as opposed to "guaranteed to be unique" you can have a look into the concepts of "UUID". You'd have to judge the useability for your purpose yourself.)