The ref
and out
keywords in C# are used when passing references to variables or structures to methods.
In TypeScript, these keywords are not available, but in ZEPETOScript, you can achieve similar functionality using $ref
and $unref
.
Functions | Description |
---|---|
$ref(x?:T):$Ref | Creates a reference for a parameter |
$unref(x:$Ref):T | Releases the reference of a parameter and returns the original value |
For the example, let's set up a Scene as follows:
- Add a 3D object, Cube, to the Scene.
- In the Inspector for the added Cube, click "Add Component" and add a Rigidbody.
- Add an Empty GameObject to the Scene.
- Write the RefSample script below and add it to the GameObject created in step 3.
import { GameObject, Rigidbody } from 'UnityEngine'
import { ZepetoScriptBehaviour } from 'ZEPETO.Script'
import TestScript from './TestScript';
export default class RefSample extends ZepetoScriptBehaviour {
Start() {
// Get the GameObject named "Cube"
const testObject = GameObject.Find("Cube");
// Get the Rigidbody Component from the "Cube" Object
const testComponent = GameObject.Find("Cube").GetComponent<Rigidbody>();
// Get the TestScript Component from the "Cube" Object
const testScript = GameObject.Find("Cube").GetComponent<TestScript>();
// Create references to the components and object
let tempObj = $ref(testObject);
let tempComponent = $ref(testComponent);
let tempScript = $ref(testScript);
// Check if the Rigidbody component is not null
if(tempComponent != null) {
// Access the actual value of that reference
let component = $unref(tempComponent);
console.log(`Component Name : ${component}`);
}
// Check if the TestScript component is not null
if(tempScript != null) {
// Access the actual value of that reference
let script = $unref(tempScript);
script.DoTest();
}
// Check if the GameObject reference is not null
if(tempObj != null) {
// Access the actual value of that reference
let objName = $unref(tempObj);
console.log(`tempObj Name : ${objName.name}`);
}
}
}
- Create another ZEPETOScript and write the TestScript below.
import { ZepetoScriptBehaviour } from 'ZEPETO.Script'
export default class TestScript extends ZepetoScriptBehaviour {
DoTest() {
console.log(`TestScript's DoTest() is executed.`);
}
}
- Drag and connect TestScript to the Cube's Inspector.
- Click the [▶︎(play)] button to observe the results.
- You can check the success of referencing objects, Rigidbody components, and ZEPETOScript components in the console log window.