Restarting a scene in react

Hello, I have a game I built here GitHub - AJTJ/gravity_ball_v2
It’s a rehashing of an old game I made with Babylon a few years ago. Many versions ago.
But I’m unable to get the scene restarting like I used to.
You can see here at line 254 (gravity_ball_v2/index.jsx at master · AJTJ/gravity_ball_v2 · GitHub) I had a window event that would simply dispose of the scene, but that doesn’t seem to work with the new (improved) SceneComponent system.

I’m sure there’s an easy solution!

Thanks,

Aaron

Hi @ajtj , welcome to the forum! :slight_smile:

I assume the event dispatch is not the issue here. If i read correctly in the source, the old scene is being disposed, and the new one is being created. any errors there? Are you making sure you are rendering the right scene?

Thanks for your reply @RaananW
I’m not sure if it is rendering correctly.
I’ve tried a couple different methods. I dropped the window.dispatchEvent(new Event("game_restart")); method, but either way I think I’m potentially performing some anti-patterns I’m not aware of here.
Currently I’m trying to call a function called gameRestart in the onSceneReady here:

…that was declared inside the SceneComponent here:

But I’m getting a Error: No camera defined error, which makes me think that the scene hasn’t been properly disposed of.
Thoughts?

@RaananW be great to hear what you think, as I’m sure there are some principles to learn here.

“No camera defined” means that the scene is rendering but doesn’t have a camera defined. You are starting a new scene, but you are not (re)creating the camera. Which port of your code is in charge of generating the camera?

hi @ajtj - When your new scene is created you need to re-run this part of the code:

if (scene.isReady()) {
  props.onSceneReady(scene, gameRestart);
} else {
  scene.onReadyObservable.addOnce((scene) =>
    props.onSceneReady(scene, gameRestart)
  );
}

The above should fix the missing camera issue.

Additionally, you should put your scene into a ref.

const sceneRef = useRef(null);

...
const scene = new Scene(...);
sceneRef.current = scene;

The reason for the ref is that your existing scene reference, which is a variable, will not be available when you re-assign it.

It looks like you have a scene key as part of your game logic. I didn’t investigate the code fully, but if you use that as a key on the component then it will automatically dispose and re-create for you.
ie:

<SceneComponent key={} onSceneReady={...} />

What the key will do when it changes is let React know to remove that component and create a new one.

edit: if you choose one of those methods then I can show more implementation details.

1 Like

Hi @ajtj just checking in, were you able to get the scene working again? :smiley: