Error while adding an Object to scene

Step 1: I’m in scene A.
This has 2 objects which are FirstObjOfA and SecondObjOfA.
When the scene is created, the FirstObjOfA is added to the scene.

Step 2: On tapping a button inside FirstObjOfA, an event is dispatched to the parent (Scene A) and SecondObjOfA is opened with some specific parameters.
Something like this:

local function sceneAEventListener(event)
if ( event.type == ‘gotoSecondObjOfA’) then
FirstObjOfA:removeSelf();
FirstObjOfA = nil;
SecondObjOfA = SecondObject.new(params)
sceneGroup:insert(SecondObjOfA);
end
Runtime:addEventListener(‘sceneA’, sceneAEventListener);

Step 3: Now on tapping of SecondObjOfA an event is dispatched to the parent where the scene is now changed (say Scene B). And Scene A is destroyed.

Step 4: In Scene B, there’s some action performed that calls ‘Scene A’. FirstObjOfA gets loaded with fresh parameters.

Step 5: On tapping a button in it, ideally SecondObjOfA should open with fresh parameters, just like in Step 2, but now the code inside sceneAEventListener with event.type == ‘gotoSecondObjOfA’ runs twice.
First with the earlier parameters passed in step 2 now again with the new parameters and there are two objects that get created.

Any idea what’s wrong? And why is the first parameters loading again.

I I’m not sure what exactly your code does, but if you don’t remove the listener (Runtime:removeEventListener(‘sceneA’, sceneAEventListener);), it is going to be called every time you dispatch said event even if the whole scene is destroyed, and once you change the scene that listener is going to be pointing to the wrong elements.

So first, you have to remove the listeners, then remove the scene and just then, create the new one.

Anyway, you have to clean up that code. I recommend to avoid dispatching Runtime events unless that is completely necessary.

Yes yes, I’m already removing the eventListener on destroy.
Anyway, I’ll see if there’s a way of not dispatching Runtime events and see if that works.

So check if the listener is not nil when you try to remove it. If not nil, check if the address is the same when you add and when you remove the listener, maybe you are adding the listener twice on creation or its scope is wrong.

1 Like