githubEdit

Scripting Examples

A collection of useful script snippets and examples.

Code snippets and examples for common tasks in Needle Engine.

:::tip New to Scripting? Start with these guides first:

More Examples:


🎯 Getting Started

Basic Component

Every component extends Behaviour and uses lifecycle methods like start() and update().

@code ts twoslasharrow-up-right

See all lifecycle methodsarrow-up-rightComponent Architecturearrow-up-right


📦 References & Assets

Reference an Object from Unity

Reference scene objects and access them at runtime.

@code ts twoslasharrow-up-right

How it works:

  1. In Unity/Blender, you assign an object to the field in the Inspector

  2. During export, the reference is saved in the glTF file with a unique identifier

  3. At runtime, Needle Engine resolves the reference and assigns the actual three.js Object3D to your field

  4. The reference is available in awake() or start() lifecycle methods

:::tip Type Safety Use @serializable(Object3D) so TypeScript knows the type. Without it, you still get the reference, but as a plain object. :::

Understanding referencesarrow-up-rightSerialization guidearrow-up-right

Reference and Load a Prefab

Load prefabs or scene assets dynamically at runtime.

@code ts twoslasharrow-up-right

How it works:

  1. Assign a prefab or scene asset in Unity/Blender Inspector

  2. The asset path is exported to the glTF

  3. Use AssetReference to load the asset on demand

  4. Call instantiate() to create instances in your scene

  5. Assets are cached after first load for better performance

:::tip Lazy Loading Prefabs are only loaded when you call instantiate(), not on scene load. This keeps initial load times fast! :::

AssetReference APIarrow-up-rightGameObject.instantiatearrow-up-right

Reference and Load Scenes

Load and unload scenes dynamically for multi-scene projects.

@code ts twoslasharrow-up-right

How it works:

  1. Reference Unity Scene assets or glTF files

  2. Scenes are exported as separate glTF files

  3. Use SceneSwitcher or load manually with AssetReference

  4. Previous scene is unloaded automatically (or kept loaded if desired)

  5. Perfect for level-based games or multi-room experiences

:::tip Live Example Try the multi-scene loading samplearrow-up-right :::

SceneSwitcher componentarrow-up-rightScene management guidearrow-up-right


🖱️ Input & Interaction

Receive Clicks on Objects

Make objects clickable by adding this script. Requires ObjectRaycaster component in parent hierarchy.

@code ts twoslasharrow-up-right

Input events referencearrow-up-rightInteraction componentsarrow-up-right

Networking Clicks (Multiplayer)

Sync clicks across all connected clients. The click event is sent to all users and can trigger animations, hide objects, etc.

@code ts twoslasharrow-up-right

:::tip Unity/Blender Integration Assign functions to the onClick event in Unity/Blender to trigger animations or other actions! :::

Networking guidearrow-up-rightSyncedRoom componentarrow-up-right


🎬 Animation

Play Animation on Click

Trigger animations when objects are clicked.

@code ts twoslasharrow-up-right

Reference Animation Clips

Access animation clips for custom animation logic. You can also export arrays of clips.

@code ts twoslasharrow-up-right

Animation componentsarrow-up-rightAnimator APIarrow-up-right


📢 Events & Serialization

Create and Invoke Unity Events

Use EventList to create events that can be configured in Unity/Blender Editor.

@code ts twoslasharrow-up-right

:::tip Component-Level Events EventList events can also be subscribed to at the component level:

This is an experimental feature. Share feedback on our forumarrow-up-right :::

Custom Event Types

Expose custom events with specific arguments (e.g., strings, numbers) to Unity/Blender.

@code ts twoslasharrow-up-right

Unity Editor integration:

Custom event in Unity

Nested Objects & Serialization

Nest custom objects with automatic serialization using @serializable decorators.

TypeScript: @code ts twoslasharrow-up-right

C# (Unity/Blender): @codearrow-up-right

:::tip Automatic Deserialization Data without type decorators still works - you'll get plain objects. Add types as needed for strongly-typed access. :::

Type system guidearrow-up-rightSerialization referencearrow-up-right


🌐 Web APIs & Browser Features

:::tip Full Web Platform Access Needle Engine gives you access to all web APIs and any npm package. Use geolocation, notifications, media devices, and more!

Browse npm packagesarrow-up-rightWeb APIs referencearrow-up-right :::

Geolocation - Display Current Location

Access the browser's Geolocation API to get the user's position.

@code ts twoslasharrow-up-right

Geolocation API docsarrow-up-right

Display Current Time (with Coroutine)

Use coroutines for time-based updates without blocking the main thread.

@code ts twoslasharrow-up-right

Coroutines guidearrow-up-right


🎨 Rendering & Visual Effects

Change Custom Shader Properties

Modify shader properties at runtime (e.g., _Speed float value).

Shader samplesarrow-up-rightMaterials guidearrow-up-right

Switching src Attribute

Dynamically change the scene being loaded.

Live example on StackBlitzarrow-up-right

Adding Custom Post-Processing Effects

Create custom post-processing effects using the pmndrs/postprocessingarrow-up-right library.

Installation:

Add the effect to the same object as your Volume component. Example wrapping the Outline effectarrow-up-right:

@codearrow-up-right

Post-processing componentsarrow-up-rightVolume APIarrow-up-right

Custom ParticleSystem Behaviour

Extend the ParticleSystem with custom behavior.

@code ts twoslasharrow-up-right

ParticleSystem APIarrow-up-rightParticles samplearrow-up-right


🔊 Audio & Media

Custom 2D Audio Component

Create a custom audio component (though AudioSource covers most use cases).

@code ts twoslasharrow-up-right

AudioSource componentarrow-up-rightAudio guidearrow-up-right


📁 File Handling

Load External Files

Use FileReference to load external files like JSON, images, or other assets.

@code ts twoslasharrow-up-right

DropListener componentarrow-up-rightFile APIarrow-up-right


HTML Integration

Receiving HTML Button Clicks in Components

Bridge HTML UI and 3D components by listening to DOM events.

How it works:

  1. Add a button or element in your HTML (index.html)

  2. Query the element with document.querySelector()

  3. Add event listener in your component's onEnable()

  4. Remove listener in onDisable() to prevent memory leaks

Example:

HTML DOM accessarrow-up-rightDOM Eventsarrow-up-right


🔆 Environment & Lighting

Disable Environment Light

Control scene lighting by disabling environment maps at runtime.

three.js Scene.environmentarrow-up-rightLighting guidearrow-up-right


🤖 Advanced Integrations

MediaPipe Hand Tracking

Control your 3D scene with hand gestures using Google's MediaPipe library.

Installation:

Try it live: MediaPipe Hands Samplearrow-up-right (requires webcam)

How it works:

  1. MediaPipe tracks hand landmarks from webcam feed

  2. Hand positions are mapped to 3D world coordinates

  3. Use landmarks to control objects, UI, or interactions

  4. Runs in real-time with excellent performance

MediaPipe Hands docsarrow-up-rightGitHub samplearrow-up-right


⚛️ Physics Examples

Change Color on Collision

Detect physics collisions and change material colors.

Physics eventsarrow-up-rightCollision APIarrow-up-right

Physics Trigger Relay

Invoke events when objects enter/exit trigger zones.

Trigger eventsarrow-up-rightEventList guide

Auto Reset Position

Reset object position when it leaves a trigger zone (e.g., respawn objects).

Play Audio on Collision

Trigger sound effects on physics collisions.

AudioSource componentarrow-up-rightAudio guidearrow-up-right

Physics documentationarrow-up-rightRapier physics enginearrow-up-right


🎲 Utility Scripts

Set Random Color

Randomize object colors on start (useful for spawned objects, testing).

:::tip Material Cloning Always clone materials when modifying them to avoid affecting other objects using the same material! :::

Spawn Objects Over Time

Instantiate objects at intervals (e.g., enemy spawning, particle effects).

Prefab loadingCoroutines alternativearrow-up-right

Last updated