Using ES6 PC scripts in a React component

Hello!

We are working on a web app that is using React. So I made a React Component that takes care of the basis (creating the canvas, creating the PC app, loading a scene, accessing a camera…). And it works very well! I can provide a sample if someone is interested.

So now I’m trying to attach scripts to my camera. At first I was using the ES5 version of the scripts and it works well but I prefer to go full ES6. So I started to rewrite some of the common scripts in ES6. Here’s mouse-input for example: https://codepen.io/BenZysberg/pen/oNPOKWq

At first I tried to use what it’s in the API doc: pc | PlayCanvas API Reference
But that didn’t work. So I removed the pc.registerScript and added an export and now it does.

Here’s how you add your script after afterwards:

import { MouseInput } from “./pcUtils/mouseInput.js”;


pc.registerScript(MouseInput);
this.camera.script.create(MouseInput); //where this.camera is a entity with a camera.

I hope it helps somebody!

2 Likes

Many thanks for showing your solution to this!

1 Like

And here’s the code for the PlayCanvas React component:

If the component is not rendered anymore, PC is unloaded so next time you render the component you will see a loading time. If you want to avoid that, always render the component and simply change the visibility of the canvas by modifying the class name.

2 Likes