#include <iostream>
#include "Foo.h"
int main()
{
if (FooRegistered)
{
auto foo = GameObjectFactory::GetInstance().SpawnGameObjectByName("Foo");
foo->doSomething();
}
return 0;
}
#pragma once
#include<iostream>
#include "GameObject.h"
ENGINE_SPAWNABLE(Foo);
class Foo : public GameObject
{
public:
Foo()
{
std::cout << "Foo created: " << this << std::endl;
}
~Foo()
{
std::cout << "Foo destroyed: " << this << std::endl;
}
void doSomething() override
{
std::cout << "Hello from Foo: " << this << std::endl;
}
};
#pragma once
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include "Object.h"
// Registers a GameObject class with the factory's registry, and connecting that to a templated SpawnGameObject function. No need to use this if the class is never spawned through the engine
#define ENGINE_SPAWNABLE(CLASSNAME) \
class CLASSNAME; \
static bool CLASSNAME##Registered = (GameObjectFactory::GetInstance().GetGameObjectRegistry()[#CLASSNAME] = &GameObjectFactory::SpawnObject<CLASSNAME>, true)
// Singleton game object factory
class GameObjectFactory
{
public:
// Gets instance of the simpleton
static GameObjectFactory& GetInstance()
{
static GameObjectFactory Instance;
return Instance;
}
// A templated function to spawn any registered GameObject
template <typename TObject>
static std::unique_ptr<Object> SpawnObject()
{
return std::make_unique<TObject>();
}
// A factory function that spawns an object of the specified class name
std::unique_ptr<Object> SpawnGameObjectByName(const std::string& Name)
{
return Registry.at(Name)();
}
std::unordered_map<std::string, std::function<std::unique_ptr<Object>()>>& GetGameObjectRegistry() // Returns the Registry
{
return Registry;
}
private:
std::unordered_map<std::string, std::function<std::unique_ptr<Object>()>> Registry; // Registry that maps class names to factory functions
};
#pragma once
class Object
{
public:
virtual ~Object() = default;
virtual void doSomething() = 0;
};
class GameObject : public Object
{
};