The SceneSwitcher can be used to dynamically load and unload extra content
Available scenes are defined in the scenes array.
Loaded scenes will be added to the SceneSwitcher's GameObject as a child and removed when another scene is loaded by the same SceneSwitcher.
Live Examples

Use the ISceneEventListener interface to listen to scene open and closing events with the ability to modify transitions and stall the scene loading process.

  • loadscene-start: Called when a scene starts loading
  • loadscene-finished: Called when a scene finished loading
  • progress: Called when a scene is loading and the progress changes
  • scene-opened: Called when a scene is loaded and added to the SceneSwitcher's GameObject
sceneSwitcher.addEventListener("loadscene-start", (e) => {
console.log("Loading scene", e.detail.scene.url);
});
sceneSwitcher.addEventListener("loadscene-finished", (e) => {
console.log("Finished loading scene", e.detail.scene.url);
});
sceneSwitcher.addEventListener("progress", (e) => {
console.log("Loading progress", e.loaded, e.total);
});
sceneSwitcher.addEventListener("scene-opened", (e) => {
console.log("Scene opened", e.detail.scene.url);
});

Hierarchy (view full)

Properties

autoLoadFirstScene: boolean = true

When enabled the first scene will be loaded when the SceneSwitcher becomes active

true
clamp: boolean = true

When enabled the current scene index will be clamped to the scenes array bounds.
For example when the last scene is loaded and clamp is true then trying to load the next() scene will not change the scene.
When clamp is false and the last scene is loaded then the first scene will be loaded instead.

true
createMenuButtons: boolean = false

When enabled will create a button for the Needle menu to switch to the next or previous scene

false
gameObject: GameObject

the object this component is attached to. Note that this is a threejs Object3D with some additional features

guid: string = "invalid"

the unique identifier for this component

loadingScene?: AssetReference

The scene that is displayed while a scene is loading.

undefined
preloadConcurrent: number = 2

how many scenes can be loaded in parallel

2
preloadNext: number = 1

how many scenes after the currently active scene should be preloaded

1
preloadPrevious: number = 1

how many scenes before the currently active scene should be preloaded

1
queryParameterName: string = "scene"

the url parameter that is set/used to store the currently loaded scene in, set to "" to disable

"scene"
sceneLoaded: EventList<SceneSwitcher> = ...

The sceneLoaded event is called when a scene/glTF is loaded and added to the scene

scenes: AssetReference[] = []

The scenes that can be loaded by the SceneSwitcher.

[]
sourceId?: string

holds the source identifier this object was created with/from (e.g. if it was part of a glTF file the sourceId holds the url to the glTF)

useHistory: boolean = true

when enabled the new scene is pushed to the browser navigation history, only works with a valid query parameter set

true
useKeyboard: boolean = true

when enabled you can switch between scenes using keyboard left, right, A and D or number keys

true
useSceneBackground: boolean = true

When enabled will automatically apply the skybox from the loaded scene

true
useSceneLighting: boolean = true

when enabled will automatically apply the environment scene lights

true
useSceneName: boolean = true

when enabled the scene name will be used as the query parameter (otherwise the scene index will be used) Needs queryParameterName set

true
useSwipe: boolean = true

when enabled you can switch between scenes using swipe (mobile only)

true

Accessors

  • get activeAndEnabled(): boolean
  • Returns boolean

    true if the object is enabled and active in the hierarchy

  • get context(): Context
  • Use the context to get access to many Needle Engine features and use physics, timing, access the camera or scene

    Returns Context

  • set context(context): void
  • Parameters

    Returns void

  • get currentIndex(): number
  • The index of the currently loaded and active scene

    Returns number

  • get currentLoadingProgress(): undefined | ProgressEvent<EventTarget>
  • Get the progress of the currently loading scene. This is undefined if no scene is loading
    You can also subscribe to the loading event by adding an event listener to the scene switcher.
    For example like this sceneSwitcher.addEventListeneer("progress", (e) => {...})

    Returns undefined | ProgressEvent<EventTarget>

  • get currentlyLoadedScene(): undefined | AssetReference
  • The currently loaded scene. This is undefined if no scene is loaded.

    Returns undefined | AssetReference

  • get currentlyLoadingScene(): undefined | AssetReference
  • The currently loading scene. This is undefined if no scene is loading.

    Returns undefined | AssetReference

  • get destroyed(): boolean
  • Returns boolean

    true if this component was destroyed (this.destroy()) or the whole object this component was part of

  • get enabled(): boolean
  • Returns boolean

  • set enabled(val): void
  • Parameters

    • val: boolean

    Returns void

  • get forward(): Vector3
  • Forward (0,0,-1) vector in world space

    Returns Vector3

  • get hideFlags(): HideFlags
  • Returns HideFlags

  • get layer(): number
  • Returns number

    the layer of the gameObject this component is attached to

  • get name(): string
  • Returns string

    the name of the gameObject this component is attached to

  • set name(str): void
  • Parameters

    • str: string

    Returns void

  • get right(): Vector3
  • Right (1,0,0) vector in world space

    Returns Vector3

  • get scene(): Scene
  • shorthand for this.context.scene

    Returns Scene

    the scene of the context

  • get static(): boolean
  • Is the gameObject marked as static

    Returns boolean

  • set static(value): void
  • Parameters

    • value: boolean

    Returns void

  • get tag(): string
  • Returns string

    the tag of the gameObject this component is attached to

  • set tag(str): void
  • Parameters

    • str: string

    Returns void

  • get up(): Vector3
  • Up (0,1,0) vector in world space

    Returns Vector3

  • get worldEuler(): Euler
  • Returns Euler

  • set worldEuler(val): void
  • Parameters

    Returns void

  • get worldPosition(): Vector3
  • Returns Vector3

  • set worldPosition(val): void
  • Parameters

    Returns void

  • get worldQuaternion(): Quaternion
  • Returns Quaternion

  • set worldQuaternion(val): void
  • Parameters

    Returns void

  • get worldRotation(): Vector3
  • Returns Vector3

  • set worldRotation(val): void
  • Parameters

    Returns void

Methods

  • Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

    The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

    When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

    When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

    When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

    If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

    The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

    MDN Reference

    Type Parameters

    Parameters

    • type: string
    • listener: ((evt: T) => any)
        • (evt): any
        • Parameters

          • evt: T

          Returns any

    Returns void

  • Add a scene to the SceneSwitcher.
    If the scene is already added it will be added again.

    Parameters

    • urlOrAssetReference: string | AssetReference

      The url of the scene or an AssetReference to the scene

    Returns AssetReference

    The AssetReference of the scene that was added

    // adding a scene:
    sceneSwitcher.addScene("scene1.glb");
    // add another scene and load it:
    const scene2 = sceneSwitcher.addScene("scene2.glb");
    sceneSwitcher.switchScene(scene2).then(res => { console.log("Scene loaded", res); });
  • Destroys this component (and removes it from the object)

    Returns void

  • Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

    MDN Reference

    Parameters

    Returns boolean

  • first callback in a frame (called every frame when implemented)

    Returns void

  • late callback in a frame (called every frame when implemented)

    Returns void

  • called before the scene gets rendered in the main update loop

    Parameters

    • frame: null | XRFrame

    Returns void

  • Called before the XR session is requested. Use this callback if you want to modify the session init features

    Parameters

    • mode: XRSessionMode
    • args: XRSessionInit

    Returns void

  • Called when the component gets destroyed

    Returns void

  • Callback when this component joins a xr session (or becomes active in a running XR session)

    Parameters

    Returns void

  • Callback when this component exists a xr session (or when it becomes inactive in a running XR session)

    Parameters

    Returns void

  • Called for all scripts when the context gets paused or unpaused

    Parameters

    • isPaused: boolean
    • wasPaused: boolean

    Returns void

  • Called when an object (or any child object) is clicked (needs a EventSystem in the scene)

    Parameters

    Returns any

  • Called when a pointer (mouse, touch, xr controller) starts pointing on/hovering an object (or a child object)

    Parameters

    Returns any

  • Called when a pointer (mouse, touch, xr controller) exists an object (it was hovering the object before but now it's not anymore)

    Parameters

    Returns any

  • Called when a pointer (mouse, touch, xr controller) is moving over an object (or a child object)

    Parameters

    Returns any

  • Called when a button is released (which was previously pressed in onPointerDown)

    Parameters

    Returns any

  • called when you decorate fields with the @validate() decorator

    Parameters

    • Optionalprop: string

      the name of the field that was changed

    Returns void

  • Callback when a controller is connected/added while in a XR session
    OR when the component joins a running XR session that has already connected controllers
    OR when the component becomes active during a running XR session that has already connected controllers

    Returns void

  • Removes the event listener in target's event listener list with the same type, callback, and options.

    MDN Reference

    Type Parameters

    Parameters

    • type: string
    • listener: ((arg: T) => any)
        • (arg): any
        • Parameters

          • arg: T

          Returns any

    Returns void

  • called on a component with a map of old to new guids (e.g. when instantiate generated new guids and e.g. timeline track bindings needs to remape them)

    Parameters

    • guidsMap: GuidsMap

    Returns void

  • Load a scene by its index in the scenes array.

    Parameters

    • index: string | number

      The index of the scene or a string that represents the scene uri (if the url is not known to the SceneSwitcher it will try to load the scene by its uri but it won't be added to the current scenes array. Use addScene to add a scene to the SceneSwitcher)

    Returns Promise<boolean>

    a promise that resolves to true if the scene was loaded successfully

  • Load the next scene in the scenes array (this.currentIndex + 1)
    If the current scene is the last scene in the array and this.clamp is disabled then the first scene will be loaded.

    Returns Promise<boolean>

    a promise that resolves to true if the scene was loaded successfully

  • Load the previous scene in the scenes array (this.currentIndex - 1)
    If the current scene is the first scene in the array and this.clamp is disabled then the last scene will be loaded.

    Returns Promise<boolean>

    a promise that resolves to true if the scene was loaded successfully

  • Parameters

    • x: number
    • y: number
    • z: number
    • w: number

    Returns void

  • Parameters

    • x: number
    • y: number
    • z: number
    • degrees: boolean = true

    Returns void

  • called at the beginning of a frame (once per component)

    Returns void

  • starts a coroutine (javascript generator function)
    yield will wait for the next frame:

    • Use yield WaitForSeconds(1) to wait for 1 second.
    • Use yield WaitForFrames(10) to wait for 10 frames.
    • Use yield new Promise(...) to wait for a promise to resolve.

    Parameters

    • routine: Generator<unknown, any, unknown>

      generator function to start

    • evt: FrameEvent = FrameEvent.Update

      event to register the coroutine for (default: FrameEvent.Update). Note that all coroutine FrameEvent callbacks are invoked after the matching regular component callbacks. For example FrameEvent.Update will be called after regular component update() methods)

    Returns Generator<unknown, any, unknown>

    the generator function (use it to stop the coroutine with stopCoroutine)

    onEnable() { this.startCoroutine(this.myCoroutine()); }
    private *myCoroutine() {
    while(this.activeAndEnabled) {
    console.log("Hello World", this.context.time.frame);
    // wait for 5 frames
    for(let i = 0; i < 5; i++) yield;
    }
    }
  • Stop a coroutine that was previously started with startCoroutine

    Parameters

    • routine: Generator<unknown, any, unknown>

      the routine to be stopped

    • evt: FrameEvent = FrameEvent.Update

      the frame event to unregister the routine from (default: FrameEvent.Update)

    Returns void

  • Optional callback, you can implement this to only get callbacks for VR or AR sessions if necessary.

    Parameters

    • mode: XRSessionMode

    Returns boolean

    true if the mode is supported (if false the mode is not supported by this component and it will not receive XR callbacks for this mode)

  • Switch to a scene by its AssetReference.
    If the scene is already loaded it will be unloaded and the new scene will be loaded.
    If the scene is already loading it will wait for the scene to be loaded.
    If the scene is already loaded and the same scene is requested again it will return the same promise that was returned the first time the scene was requested.

    Parameters

    Returns Promise<boolean>

    a promise that resolves to true if the scene was loaded successfully

    const myAssetReference = new AssetReference("scene1.glb");
    sceneSwitcher.switchScene(myAssetReference).then(res => { console.log("Scene loaded", res); });
  • regular callback in a frame (called every frame when implemented)

    Returns void