haku
March 10, 2022, 2:47am
#1
JS scripts created under the editor, how to introduce and use in non-editor scripts. There are no examples. For example, the orbitCamera script, how can I use it.
Hi @haku ,
Check the following helper script in the engine repo. It’s being used extensively in the engine examples to load assets, and script assets, so they are made available much like in the editor:
name: string,
type: string,
data?: any,
url?: string
}
class AssetLoader extends React.Component <AssetLoaderProps, any> {
static ctor: any;
static load(resource: AssetLoaderProps, app: pc.Application, onLoad: any) {
if (resource.data) {
const asset = new pc.Asset(resource.name, resource.type, resource.type === 'cubemap' ? { url: resource.url } : null, resource.data);
asset.on('load', function (asset) {
onLoad(resource.name, asset);
});
app.assets.add(asset);
app.assets.load(asset);
} else {
app.assets.loadFromUrl(resource.url, resource.type, function (err, asset) {
if (!err && asset) {
onLoad(resource.name, asset);
}
Code example on how to use it:
import React from 'react';
import * as pc from '../../../../';
import { AssetLoader } from '../../app/helpers/loader';
class OrbitExample {
static CATEGORY = 'Camera';
static NAME = 'Orbit';
load() {
return <>
<AssetLoader name='statue' type='container' url='/static/assets/models/statue.glb' />
<AssetLoader name='script' type='script' url='/static/scripts/camera/orbit-camera.js' />
</>;
}
example(canvas: HTMLCanvasElement, assets: { statue: pc.Asset, script: pc.Asset }): void {
// Create the app and start the update loop
const app = new pc.Application(canvas, {
This file has been truncated. show original
1 Like
haku
March 11, 2022, 2:17am
#3
Thank you so much. This example uses the React library, which I’m not familiar with its syntax, is there any example based on ordinary JavaScript.
After the PlayCanvas application object has been created, you can use app.assets.loadFromUrl with the URL of the script.
Once the script asset has been loaded, then you can add it to a script component of an entity