Accessing Components
- Available on all platforms
Script Components in Lens Studio are able to reference one another whether they have been created with JavaScript, TypeScript or Custom Component.
Accessing JavaScript from JavaScript
To access properties and methods of a Component created with JavaScript, the property or method must be declared to a predefined object which all ScriptComponent have called script. In the example code below script.numberVal is declared and made available for other scripts to access it.
script.numberVal = 1;
script.printHelloWorld = function () {
print('hello');
};
//@input Component.ScriptComponent refScript
print(script.refScript.numberVal);
script.refScript.printHelloWorld();
In this practical example, ComponentA provides several utilities including properties, methods, and error handling, while ComponentB demonstrates how to access and use these features.
/**
* AccessJSfromJS_ComponentA.js
*
* This component provides various properties and methods that can be accessed by other scripts.
* It simulates a utility component that manages game state and provides helper functions.
*/
//@input bool debug {"label":"Debug Mode", "hint":"Enable debug logging"}
// Initialize component properties
script.numberVal = 1;
script.textValue = 'Hello World';
script.isActive = true;
script.lastUpdated = new Date().toISOString();
script.config = {
maxValue: 100,
minValue: 0,
defaultSpeed: 5,
};
// Counter for tracking method calls
let callCounter = 0;
/**
* Print a hello message to the console
*/
script.printHelloWorld = function () {
callCounter++;
script.debug && print('Hello World! (Call #' + callCounter + ')');
return 'Hello World';
};
/**
* Increment the number value by the specified amount
* @param {number} amount - The amount to increment by (default: 1)
* @returns {number} The new value
*/
script.incrementNumber = function (amount) {
amount = amount || 1;
script.numberVal += amount;
script.lastUpdated = new Date().toISOString();
script.debug && print('Number incremented to: ' + script.numberVal);
return script.numberVal;
};
/**
* Set a new text value
* @param {string} newText - The new text value
* @returns {string} The new text value
*/
script.setText = function (newText) {
if (typeof newText !== 'string') {
print('Error: setText requires a string parameter');
return script.textValue;
}
script.textValue = newText;
script.lastUpdated = new Date().toISOString();
script.debug && print('Text set to: ' + script.textValue);
return script.textValue;
};
/**
* Toggle the active state
* @returns {boolean} The new active state
*/
script.toggleActive = function () {
script.isActive = !script.isActive;
script.lastUpdated = new Date().toISOString();
script.debug && print('Active state toggled to: ' + script.isActive);
return script.isActive;
};
/**
* Get the current component status
* @returns {Object} An object containing the current status
*/
script.getStatus = function () {
const status = {
numberVal: script.numberVal,
textValue: script.textValue,
isActive: script.isActive,
lastUpdated: script.lastUpdated,
callCount: callCounter,
};
script.debug && print('Status requested: ' + JSON.stringify(status));
return status;
};
// Initialize the component
script.debug &&
print('ComponentA initialized with numberVal: ' + script.numberVal);
/**
* AccessJSfromJS_JSComponentB.js
*
* This component demonstrates how to access and interact with another JavaScript component.
* It uses the reference to ComponentA to call its methods and access its properties.
*/
//@input Component.ScriptComponent refScript {"label":"Component A", "hint":"Reference to ComponentA script"}
//@input bool debug {"label":"Debug Mode", "hint":"Enable debug logging"}
//@input int updateInterval = 60 {"label":"Update Interval", "hint":"Frames between updates", "min":1, "max":300}
// Counter for tracking frames
let frameCounter = 0;
// Create an event for onStart to ensure components are fully initialized
script.createEvent('OnStartEvent').bind(onStart);
// Create an event for update to demonstrate continuous interaction
script.createEvent('UpdateEvent').bind(onUpdate);
/**
* Called when the script starts
*/
function onStart() {
try {
// Verify that the reference script exists
if (!script.refScript) {
print(
'Error: Reference to ComponentA is missing. Please set it in the Inspector.'
);
return;
}
script.debug && print('ComponentB initialized, connected to ComponentA');
// Access properties from ComponentA
script.debug &&
print('Initial number value: ' + script.refScript.numberVal);
script.debug && print('Initial text value: ' + script.refScript.textValue);
script.debug && print('Initial active state: ' + script.refScript.isActive);
// Call methods on ComponentA
script.refScript.printHelloWorld();
script.refScript.incrementNumber(5);
script.refScript.setText('Updated from ComponentB');
// Get and display the current status
const status = script.refScript.getStatus();
script.debug && print('Current status: ' + JSON.stringify(status));
// Demonstrate error handling
try {
// Intentionally call setText with a non-string parameter
script.refScript.setText(123);
} catch (error) {
script.debug && print('Caught error: ' + error);
}
} catch (error) {
print('Error in onStart: ' + error);
}
}
/**
* Called every frame
*/
function onUpdate() {
try {
// Only run this code at the specified interval
frameCounter++;
if (frameCounter % script.updateInterval !== 0) return;
// Skip if reference script is missing
if (!script.refScript) return;
// Demonstrate continuous interaction with ComponentA
if (script.refScript.isActive) {
// Increment the number value
const newValue = script.refScript.incrementNumber(1);
script.debug && print('Updated number value: ' + newValue);
// Toggle active state every 5 updates
if (frameCounter % (script.updateInterval * 5) === 0) {
const isActive = script.refScript.toggleActive();
script.debug && print('Toggled active state to: ' + isActive);
}
} else {
// If not active, just print the current status
const status = script.refScript.getStatus();
script.debug &&
print('Component is inactive. Last updated: ' + status.lastUpdated);
// Reactivate after 3 updates
if (frameCounter % (script.updateInterval * 3) === 0) {
script.refScript.toggleActive();
script.debug && print('Reactivated component');
}
}
} catch (error) {
print('Error in onUpdate: ' + error);
}
}
Accessing TypeScript from JavaScript
To access properties and methods of a Component created with TypeScript, the property or method must be declared within the scoped TypeScript defined Class. Properties and methods defined in a TypeScript file are by default public members. In the example code below numberVal is declared within the scope of the class TSComponentA and made available for other scripts to access it.
@component
export class TSComponentA extends BaseScriptComponent {
numberVal: number = 1;
onAwake() {}
printHelloWorld() {
print('Hello, world!');
}
}
//@input Component.ScriptComponent refScript
print(script.refScript.numberVal);
script.refScript.printHelloWorld();
In this example, a TypeScript component provides a rich set of properties and methods that are accessed from a JavaScript component.
/**
* A feature-rich TypeScript component that exposes various properties and methods
*/
@component
export class TSComponentA extends BaseScriptComponent {
// Debug flag accessible from outside
@input
debug: boolean = true;
// Public properties accessible from JavaScript
numberVal: number = 1;
stringVal: string = 'Hello from TSComponentA';
boolVal: boolean = true;
arrayVal: number[] = [10, 20, 30, 40, 50];
objectVal = {
name: 'TSComponentA',
version: 2.0,
features: ['strongTyping', 'inheritance', 'interfaces'],
};
// Private state (not accessible from JavaScript)
private counter: number = 0;
private lastCalledMethod: string = '';
onAwake() {
this.debug && print('[TSComponentA] Initialized');
}
// Public methods accessible from JavaScript
printHelloWorld(): void {
this.lastCalledMethod = 'printHelloWorld';
print('Hello, world!');
}
getComponentInfo() {
this.lastCalledMethod = 'getComponentInfo';
const info = {
name: this.objectVal.name,
version: this.objectVal.version,
lastCalled: this.lastCalledMethod,
};
return info;
}
calculateAverage(numbers) {
this.lastCalledMethod = 'calculateAverage';
if (numbers.length === 0) return 0;
const sum = numbers.reduce((a, b) => a + b, 0);
return sum / numbers.length;
}
incrementCounter(amount = 1) {
this.lastCalledMethod = 'incrementCounter';
this.counter += amount;
return this.counter;
}
resetCounter() {
this.lastCalledMethod = 'resetCounter';
this.counter = 0;
return this.counter;
}
getCounter() {
this.lastCalledMethod = 'getCounter';
return this.counter;
}
}
/**
* JavaScript component that accesses a TypeScript component
*/
//@input Component.ScriptComponent refScript {"label":"TS Component", "hint":"Reference to TSComponentA"}
//@input bool debug {"label":"Debug Mode", "hint":"Enable debug logging"}
// Initialize on start
script.createEvent('OnStartEvent').bind(function () {
if (!script.refScript) {
print('Error: TypeScript component reference is missing!');
return;
}
// Access basic properties
script.debug && print('Accessing TypeScript properties from JavaScript:');
script.debug && print('Number value: ' + script.refScript.numberVal);
script.debug && print('String value: ' + script.refScript.stringVal);
script.debug && print('Boolean value: ' + script.refScript.boolVal);
script.debug &&
print('Array value: ' + JSON.stringify(script.refScript.arrayVal));
script.debug &&
print('Object value: ' + JSON.stringify(script.refScript.objectVal));
// Call methods
script.debug && print('\nCalling TypeScript methods from JavaScript:');
script.refScript.printHelloWorld();
const info = script.refScript.getComponentInfo();
script.debug && print('Component info: ' + JSON.stringify(info));
const average = script.refScript.calculateAverage(script.refScript.arrayVal);
script.debug && print('Average of array values: ' + average);
// Manipulate counter
script.debug && print('\nUsing counter methods:');
script.debug && print('Initial counter: ' + script.refScript.getCounter());
script.debug &&
print('After increment: ' + script.refScript.incrementCounter());
script.debug &&
print('After increment by 5: ' + script.refScript.incrementCounter(5));
script.debug && print('After reset: ' + script.refScript.resetCounter());
// Private properties are not accessible
script.debug && print('\nTrying to access private properties:');
if (script.refScript.counter === undefined) {
script.debug && print("Private property 'counter' is not accessible");
}
if (script.refScript.lastCalledMethod === undefined) {
script.debug &&
print("Private property 'lastCalledMethod' is not accessible");
}
});
// Add utility methods that wrap TypeScript functionality
script.incrementTSCounter = function (amount) {
if (!script.refScript) return 0;
return script.refScript.incrementCounter(amount);
};
script.resetTSCounter = function () {
if (!script.refScript) return 0;
return script.refScript.resetCounter();
};
script.getTSAverage = function (numbers) {
if (!script.refScript) return 0;
return script.refScript.calculateAverage(numbers);
};
Accessing TypeScript from TypeScript
ScriptComponent created with TypeScript can be accessed directly with the Class type. In the example below, TSComponentA is created and being referenced by TSComponentB. To access the TSComponentA's property and methods, a reference property @input with the type TSComponentA is declared in TSComponentB.
@component
export class TSComponentA extends BaseScriptComponent {
numberVal: number = 1;
onAwake() {}
printHelloWorld() {
print('Hello, world!');
}
}
import { TSComponentA } from './TSComponentA';
@component
export class TSComponentB extends BaseScriptComponent {
@input
refScript: TSComponentA;
onAwake() {
print(this.refScript.numberVal);
this.refScript.printHelloWorld();
}
}
In this comprehensive example, a TypeScript component leverages full type safety when accessing another TypeScript component.
/**
* TypeScript component that can be accessed from another TypeScript component
* with full type safety and intellisense
*/
@component
export class TSComponentA extends BaseScriptComponent {
// Debug flag
@input
debug: boolean = true;
// Basic properties
numberVal: number = 1;
stringVal: string = 'Hello from TSComponentA';
boolVal: boolean = true;
arrayVal: number[] = [10, 20, 30, 40, 50];
objectVal: Record<string, any> = {
name: 'TSComponentA',
version: 2.0,
features: ['strongTyping', 'inheritance', 'interfaces'],
};
// Private state
private counter: number = 0;
private lastCalledMethod: string = '';
onAwake() {
this.log('TSComponentA initialized');
}
// Helper method for debug logging
private log(message: string): void {
this.debug && print(`[TSComponentA] ${message}`);
}
// Original method enhanced with debug
printHelloWorld(): void {
this.lastCalledMethod = 'printHelloWorld';
this.debug && print('Hello, world!');
}
// New methods with TypeScript type definitions
getComponentInfo(): { name: string; version: number; lastCalled: string } {
this.lastCalledMethod = 'getComponentInfo';
const info = {
name: this.objectVal.name,
version: this.objectVal.version,
lastCalled: this.lastCalledMethod,
};
this.log(`Component info requested: ${JSON.stringify(info)}`);
return info;
}
// Generic method with type parameters
processData<T>(data: T): { processed: T; timestamp: number } {
this.lastCalledMethod = 'processData';
const result = {
processed: data,
timestamp: Date.now(),
};
this.log(`Data processed: ${JSON.stringify(result)}`);
return result;
}
calculateAverage(numbers: number[]): number {
this.lastCalledMethod = 'calculateAverage';
if (numbers.length === 0) return 0;
const sum = numbers.reduce((a, b) => a + b, 0);
const avg = sum / numbers.length;
this.log(`Calculated average of [${numbers.join(', ')}] = ${avg}`);
return avg;
}
// Counter methods
incrementCounter(amount: number = 1): number {
this.lastCalledMethod = 'incrementCounter';
this.counter += amount;
this.log(`Counter incremented by ${amount} to ${this.counter}`);
return this.counter;
}
resetCounter(): number {
this.lastCalledMethod = 'resetCounter';
this.counter = 0;
this.log('Counter reset to 0');
return this.counter;
}
getCounter(): number {
this.lastCalledMethod = 'getCounter';
return this.counter;
}
// Get last called method
getLastCalledMethod(): string {
return this.lastCalledMethod;
}
// Toggle debug mode
toggleDebug(): void {
this.debug = !this.debug;
this.lastCalledMethod = 'toggleDebug';
this.debug && this.log(`Debug mode ${this.debug ? 'enabled' : 'disabled'}`);
}
}
import { TSComponentA } from './AccessTSfromTS_TSComponentA';
/**
* TypeScript component that demonstrates accessing another TypeScript component
* with full type safety and intellisense
*/
@component
export class TSComponentB extends BaseScriptComponent {
// Reference to TSComponentA with proper typing
@input
refScript: TSComponentA;
// Debug flag
@input
debug: boolean = true;
// Track if component is initialized
private initialized: boolean = false;
// Helper method for debug logging
private log(message: string): void {
this.debug && print(`[TSComponentB] ${message}`);
}
onAwake() {
if (!this.refScript) {
this.log('Error: TSComponentA reference is missing!');
return;
}
this.initialized = true;
// Sync debug settings
this.refScript.debug = this.debug;
this.log('Debug settings synchronized with TSComponentA');
// Access basic properties with full type safety
this.log('Number value: ' + this.refScript.numberVal);
this.log('String value: ' + this.refScript.stringVal);
this.log('Boolean value: ' + this.refScript.boolVal);
this.log('Array value: ' + JSON.stringify(this.refScript.arrayVal));
this.log('Object value: ' + JSON.stringify(this.refScript.objectVal));
// Call the original method
this.refScript.printHelloWorld();
this.log('Last called method: ' + this.refScript.getLastCalledMethod());
// Use component info method with type safety
const info = this.refScript.getComponentInfo();
this.log(
`Component info: name=${info.name}, version=${info.version}, lastCalled=${info.lastCalled}`
);
// Use generic data processing methods
const processedData = this.refScript.processData({
id: 123,
name: 'Test Data',
});
this.log(`Processed data timestamp: ${processedData.timestamp}`);
const average = this.refScript.calculateAverage(this.refScript.arrayVal);
this.log(`Average of array values: ${average}`);
// Use counter methods
this.log('Initial counter: ' + this.refScript.getCounter());
this.log('After increment: ' + this.refScript.incrementCounter());
this.log('After increment by 5: ' + this.refScript.incrementCounter(5));
this.log('After reset: ' + this.refScript.resetCounter());
}
// Public methods that could be called from elsewhere
public getComponentInfo(): {
name: string;
version: number;
lastCalled: string;
} | null {
if (!this.initialized || !this.refScript) return null;
return this.refScript.getComponentInfo();
}
public incrementCounter(amount: number = 1): number {
if (!this.initialized || !this.refScript) return 0;
const newValue = this.refScript.incrementCounter(amount);
this.debug &&
this.log(`Counter incremented from TSComponentB: ${newValue}`);
return newValue;
}
public resetCounter(): number {
if (!this.initialized || !this.refScript) return 0;
const newValue = this.refScript.resetCounter();
this.debug && this.log(`Counter reset from TSComponentB: ${newValue}`);
return newValue;
}
// Toggle debug mode for both components
public toggleDebug(): void {
this.debug = !this.debug;
if (this.initialized && this.refScript) {
this.refScript.debug = this.debug;
this.refScript.toggleDebug();
}
this.debug && this.log(`Debug mode ${this.debug ? 'enabled' : 'disabled'}`);
}
}
Accessing JavaScript from TypeScript
With Type Completion:
TypeScript enhances coding by providing automatic code completion. To ensure this feature works consistently when using JavaScript files, it's advised to create a declaration file. This file describes the JavaScript code structure so that your TypeScript components can recognize and work with it seamlessly. After setting up a declaration file, you can access a JavaScript component in TypeScript using the @input decorator.
Please refer to the example code below.
script.numberVal = 1;
script.printHelloWorld = function () {
print('hello');
};
export interface JSComponentA extends ScriptComponent {
numberVal: number;
printHelloWorld: () => void;
}
import { JSComponentA } from './JSComponentA_Declaration';
@component
export class TSComponentB extends BaseScriptComponent {
@input('Component.ScriptComponent')
refScript: JSComponentA;
onAwake() {
print(this.refScript.numberVal);
this.refScript.printHelloWorld();
}
}
A more comprehensive example of accessing JavaScript from TypeScript using a declaration file:
// Basic properties
script.numberVal = 1;
script.stringVal = 'Hello from JS';
script.boolVal = true;
script.arrayVal = [1, 2, 3, 4, 5];
script.objectVal = { name: 'JSComponent', version: 1.0 };
// Methods
script.printHelloWorld = function () {
print('hello');
};
script.add = function (a, b) {
return a + b;
};
script.multiply = function (a, b) {
return a * b;
};
// Event callback example
script.onValueChanged = function (callback) {
script.valueChangedCallback = callback;
};
// Method that triggers the callback
script.updateValue = function (newValue) {
script.numberVal = newValue;
if (script.valueChangedCallback) {
script.valueChangedCallback(newValue);
}
};
@component
export class Declaration extends BaseScriptComponent {
// This empty class is required to avoid editor errors
// It serves as the declaration for the JavaScript component
}
/**
* Interface for the JavaScript component that allows TypeScript to access its properties and methods
*/
export interface JSComponentA extends ScriptComponent {
// Properties
numberVal: number;
stringVal: string;
boolVal: boolean;
arrayVal: number[];
objectVal: {
name: string;
version: number;
};
// Methods
printHelloWorld: () => void;
add: (a: number, b: number) => number;
multiply: (a: number, b: number) => number;
// Event handling
onValueChanged: (callback: (newValue: number) => void) => void;
updateValue: (newValue: number) => void;
// Internal property (not meant to be accessed directly)
valueChangedCallback?: (newValue: number) => void;
}
import { JSComponentA } from './JSComponentA_Declaration';
/**
* TypeScript component that demonstrates accessing a JavaScript component
* through a TypeScript declaration file
*/
@component
export class TSComponentB extends BaseScriptComponent {
@input('Component.ScriptComponent')
refScript: JSComponentA;
// Track the current value for display
private currentValue: number = 0;
onAwake() {
// Access basic properties
print('Number value: ' + this.refScript.numberVal);
print('String value: ' + this.refScript.stringVal);
print('Boolean value: ' + this.refScript.boolVal);
print('Array value: ' + JSON.stringify(this.refScript.arrayVal));
print('Object value: ' + JSON.stringify(this.refScript.objectVal));
// Call methods
this.refScript.printHelloWorld();
const sum = this.refScript.add(5, 3);
print('5 + 3 = ' + sum);
const product = this.refScript.multiply(4, 7);
print('4 * 7 = ' + product);
// Set up event handling
this.refScript.onValueChanged(this.handleValueChanged.bind(this));
// Update the value to trigger the callback
this.refScript.updateValue(42);
}
// Event handler for value changes
private handleValueChanged(newValue: number): void {
this.currentValue = newValue;
print('Value changed to: ' + newValue);
}
// Example of a method that could be called from elsewhere
public incrementValue(): void {
if (this.refScript) {
this.refScript.updateValue(this.currentValue + 1);
}
}
}
Without Type Completion:
To access properties and methods created from JavaScript Components in your TypeScript Component without a declaration file, use the @input decorator and set the type to any.
script.numberVal = 1;
script.printHelloWorld = function () {
print('hello');
};
@component
export class TSComponentB extends BaseScriptComponent {
@input('Component.ScriptComponent')
refScript: any;
onAwake() {
print(this.refScript.numberVal);
this.refScript.printHelloWorld();
}
}
A more comprehensive example of accessing JavaScript from TypeScript without a declaration file:
// Basic properties
script.numberVal = 1;
script.stringVal = 'Hello from JS';
script.boolVal = true;
script.arrayVal = [1, 2, 3, 4, 5];
script.objectVal = { name: 'JSComponent', version: 1.0 };
// Methods
script.printHelloWorld = function () {
print('hello from JavaScript component');
};
script.calculateSum = function (numbers) {
return numbers.reduce(function (a, b) {
return a + b;
}, 0);
};
script.processData = function (data, callback) {
// Simulate processing
print('Processing data: ' + JSON.stringify(data));
// Call the callback when done
if (callback && typeof callback === 'function') {
callback({
processed: true,
result: 'Processed ' + data.name,
timestamp: Date.now(),
});
}
};
/**
* TypeScript component that demonstrates accessing a JavaScript component
* without a declaration file using 'any' type
*/
@component
export class TSComponentB extends BaseScriptComponent {
// Note: We're using 'any' type since we don't have a declaration file
@input('Component.ScriptComponent')
refScript: any;
@input
debug: boolean = true;
private log(message: string): void {
this.debug && print(`[TSComponentB] ${message}`);
}
onAwake() {
if (!this.refScript) {
this.log('Error: JavaScript component reference is missing!');
return;
}
// Access basic properties
// Note: No type checking or auto-completion for these properties
this.log('Number value: ' + this.refScript.numberVal);
this.log('String value: ' + this.refScript.stringVal);
this.log('Boolean value: ' + this.refScript.boolVal);
this.log('Array value: ' + JSON.stringify(this.refScript.arrayVal));
this.log('Object value: ' + JSON.stringify(this.refScript.objectVal));
// Call methods
this.refScript.printHelloWorld();
// We can still use TypeScript typing for local variables
const numbers: number[] = this.refScript.arrayVal;
const sum: number = this.refScript.calculateSum(numbers);
this.log(`Sum of array values: ${sum}`);
// We can define our own typing for callback functions
interface ProcessResult {
processed: boolean;
result: string;
timestamp: number;
}
// Use the callback with our own typing
this.refScript.processData(
{ name: 'Test Data', id: 123 },
(result: ProcessResult) => {
this.log(`Process complete: ${result.result}`);
this.log(`Timestamp: ${new Date(result.timestamp).toISOString()}`);
}
);
// Type safety is not enforced for property access
// This won't show an error in the editor but would fail at runtime
try {
const nonExistentMethod = this.refScript.methodThatDoesntExist();
this.log("This shouldn't be reached");
} catch (error) {
this.log('Error caught: Property access to non-existent method');
}
}
}
Accessing Components on Scene Objects
Components can be accessed directly from SceneObjects using the getComponent method. This is useful when you want to access components that are attached to specific objects in your scene hierarchy.
- JavaScript
- TypeScript
//@input SceneObject mySceneObject {"hint":"The object to access the component from"}
// Access a component on the provided scene object
let renderMeshVisual = script.mySceneObject.getComponent(
'Component.RenderMeshVisual'
);
// Check if the component exists before using it
if (renderMeshVisual) {
print('Found RenderMeshVisual component');
// Do something with the component
}
@component
export class AccessComponent extends BaseScriptComponent {
@input
mySceneObject: SceneObject;
onAwake() {
// Access a component on the provided scene object
const renderMeshVisual = this.mySceneObject.getComponent(
'Component.RenderMeshVisual'
);
// Check if the component exists before using it
if (renderMeshVisual) {
print('Found RenderMeshVisual component');
// Do something with the component
}
}
}
This example shows how to access components on specific scene objects.
//@input SceneObject mySceneObject {"hint":"The object to access the component from"}
//@input bool debug {"hint":"Show logs in the console"}
var AccessComponentOnSceneObjectJS = function () {
this.onAwake = function () {
script.createEvent('OnStartEvent').bind(() => {
this.onStart();
script.debug && print('Start event triggered');
});
};
this.onStart = function () {
script.debug && print('onAwake');
if (script.mySceneObject !== null) {
script.debug && print('Scene object is not null');
script.debug && print('Scene object name: ' + script.mySceneObject.name);
}
if (script.mySceneObject.getComponent('Component.RenderMeshVisual')) {
script.debug && print('Scene object has a RenderMeshVisual component');
} else {
script.debug &&
print('Scene object does not have a RenderMeshVisual component');
}
};
};
// Initialize the script
var instance = new AccessComponentOnSceneObjectJS();
instance.onAwake();
@component
export class AccessComponentOnSceneObjectTS extends BaseScriptComponent {
@input
@allowUndefined
@hint('The object to access the component from')
mySceneObject: SceneObject;
@input
@allowUndefined
@hint('Show logs in the console')
debug: boolean;
onAwake() {
this.createEvent('OnStartEvent').bind(() => {
this.onStart();
this.debug && print('Start event triggered');
});
}
onStart() {
this.debug && print('onAwake');
if (this.mySceneObject !== null) {
this.debug && print('Scene object is not null');
this.debug && print('Scene object name: ' + this.mySceneObject.name);
}
if (
this.mySceneObject
.getComponent('Component.RenderMeshVisual')
.getTypeName()
) {
this.debug && print('Scene object has a RenderMeshVisual component');
} else {
this.debug &&
print('Scene object does not have a RenderMeshVisual component');
}
}
}
Accessing Components on Child Scene Objects
To access components on child objects in your scene hierarchy, you can use the getChild method to navigate the scene tree and then use getComponent on the child object.
- JavaScript
- TypeScript
//@input SceneObject parentObject
// Access the first child of the parent object
let childObject = script.parentObject.getChild(0);
// Access a component on the child object
if (childObject) {
let childComponent = childObject.getComponent('Component.ScriptComponent');
if (childComponent) {
print('Found script component on child');
// Use the component
}
}
@component
export class AccessChildComponent extends BaseScriptComponent {
@input
parentObject: SceneObject;
onAwake() {
// Access the first child of the parent object
const childObject = this.parentObject.getChild(0);
// Access a component on the child object
if (childObject) {
const childComponent = childObject.getComponent(
'Component.ScriptComponent'
);
if (childComponent) {
print('Found script component on child');
// Use the component
}
}
}
}
This example demonstrates how to access components on child scene objects.
//@input SceneObject parentSceneObject {"hint":"The parent scene object to access"}
//@input bool debug {"hint":"Show logs in the console"}
var AccessComponentOnChildSceneObjectJS = function () {
this.onAwake = function () {
script.createEvent('OnStartEvent').bind(() => {
this.onStart();
script.debug && print('Start event triggered');
});
};
this.onStart = function () {
script.debug && print('onAwake');
if (
script.parentSceneObject !== null &&
script.parentSceneObject.getChild(0) !== null
) {
script.debug && print('Parent scene object is not null');
script.debug &&
print('Parent scene object name: ' + script.parentSceneObject.name);
script.debug &&
print(
'Parent child object name: ' +
script.parentSceneObject.getChild(0).name
);
}
if (
script.parentSceneObject
.getChild(0)
.getComponent('Component.RenderMeshVisual')
) {
script.debug &&
print('Parent child object has a RenderMeshVisual component');
} else {
script.debug &&
print('Parent child object does not have a RenderMeshVisual component');
}
};
};
// Initialize the script
var instance = new AccessComponentOnChildSceneObjectJS();
instance.onAwake();
@component
export class AccessComponentOnChildSceneObjectTS extends BaseScriptComponent {
@input
@allowUndefined
@hint('The parent component')
parentSceneobject: SceneObject;
@input
@allowUndefined
@hint('Show logs in the console')
debug: boolean;
onAwake() {
this.createEvent('OnStartEvent').bind(() => {
this.onStart();
this.debug && print('Start event triggered');
});
}
onStart() {
this.debug && print('onAwake');
if (
this.parentSceneobject !== null &&
this.parentSceneobject.getChild(0) !== null
) {
this.debug && print('Parent scene object is not null');
this.debug &&
print('Parent scene object name: ' + this.parentSceneobject.name);
this.debug &&
print(
'Parent child object name: ' + this.parentSceneobject.getChild(0).name
);
}
if (
this.parentSceneobject
.getChild(0)
.getComponent('Component.RenderMeshVisual')
.getTypeName()
) {
this.debug &&
print('Parent child object has a RenderMeshVisual component');
} else {
this.debug &&
print('Parent child object does not have a RenderMeshVisual component');
}
}
}