Browse Source

Fix instantiating multiple native scripts and their cleanup

master
Riyyi 4 years ago
parent
commit
a41f8467b4
  1. 14
      inferno/src/inferno/scene/components.h
  2. 2
      inferno/src/inferno/scene/scene.cpp
  3. 4
      inferno/src/inferno/systems/script.cpp

14
inferno/src/inferno/scene/components.h

@ -61,8 +61,7 @@ namespace Inferno {
struct NativeScriptComponent {
NativeScript* instance = nullptr;
std::function<void()> initialize = nullptr;
std::function<void()> destroy = nullptr;
NativeScript* (*initialize)();
// Dont allow manually setting instance during construction
NativeScriptComponent() {}
@ -70,9 +69,14 @@ namespace Inferno {
template<typename T>
void bind()
{
ASSERT(initialize == nullptr && destroy == nullptr, "NativeScript already bound");
initialize = [&]() { instance = static_cast<NativeScript*>(new T()); };
destroy = [&]() { delete instance; instance = nullptr; initialize = nullptr; destroy = nullptr; };
ASSERT(instance == nullptr, "NativeScript already bound");
initialize = []() { return static_cast<NativeScript*>(new T()); };
}
void destroy() {
ASSERT(instance, "Attempting to destroy an uninitialized NativeScript");
delete instance;
instance = nullptr;
}
};

2
inferno/src/inferno/scene/scene.cpp

@ -95,7 +95,7 @@ namespace Inferno {
void Scene::destroyEntity(uint32_t entity)
{
if (hasComponent<NativeScript>(entity)) {
if (hasComponent<NativeScriptComponent>(entity)) {
ScriptSystem::the().cleanup(entity);
}

4
inferno/src/inferno/systems/script.cpp

@ -40,7 +40,7 @@ namespace Inferno {
// Create script if not initialized
if (!nativeScript.instance) {
nativeScript.initialize();
nativeScript.instance = nativeScript.initialize();
nativeScript.instance->transform = &transform;
nativeScript.instance->m_scene = m_scene;
nativeScript.instance->m_entity = static_cast<uint32_t>(entity);
@ -56,7 +56,7 @@ namespace Inferno {
{
auto& nativeScript = m_scene->getComponent<NativeScriptComponent>(entity);
if (!nativeScript.instance) {
if (nativeScript.instance) {
nativeScript.instance->destroy();
nativeScript.destroy();
}

Loading…
Cancel
Save