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 { struct NativeScriptComponent {
NativeScript* instance = nullptr; NativeScript* instance = nullptr;
std::function<void()> initialize = nullptr; NativeScript* (*initialize)();
std::function<void()> destroy = nullptr;
// Dont allow manually setting instance during construction // Dont allow manually setting instance during construction
NativeScriptComponent() {} NativeScriptComponent() {}
@ -70,9 +69,14 @@ namespace Inferno {
template<typename T> template<typename T>
void bind() void bind()
{ {
ASSERT(initialize == nullptr && destroy == nullptr, "NativeScript already bound"); ASSERT(instance == nullptr, "NativeScript already bound");
initialize = [&]() { instance = static_cast<NativeScript*>(new T()); }; initialize = []() { return static_cast<NativeScript*>(new T()); };
destroy = [&]() { delete instance; instance = nullptr; initialize = nullptr; destroy = nullptr; }; }
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) void Scene::destroyEntity(uint32_t entity)
{ {
if (hasComponent<NativeScript>(entity)) { if (hasComponent<NativeScriptComponent>(entity)) {
ScriptSystem::the().cleanup(entity); ScriptSystem::the().cleanup(entity);
} }

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

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

Loading…
Cancel
Save