$ref & $unref
5 นาที
The ref and out คำสำคัญใน C# ถูกใช้เมื่อส่งผ่านการอ้างอิงไปยังตัวแปรหรือโครงสร้างไปยังวิธีการ.
ใน TypeScript, คำสำคัญเหล่านี้ไม่มีให้ใช้, แต่ใน ZEPETOScript, คุณสามารถทำให้ฟังก์ชันการทำงานที่คล้ายกันได้โดยใช้ $ref และ $unref.
ฟังก์ชัน | คำอธิบาย |
|---|---|
$ref(x?:T):$Ref | สร้างการอ้างอิงสำหรับพารามิเตอร์ |
$unref(x:$Ref):T | ปล่อยการอ้างอิงของพารามิเตอร์และคืนค่าต้นฉบับ |
สำหรับตัวอย่าง, มาตั้งค่า Scene ดังนี้:
- เพิ่มวัตถุ 3D, ลูกบาศก์, ลงในฉาก.

- ใน Inspector สำหรับลูกบาศก์ที่เพิ่มเข้ามา ให้คลิก "Add Component" และเพิ่ม Rigidbody.

- เพิ่ม GameObject เปล่าในฉาก.
- เขียนสคริปต์ RefSample ด้านล่างและเพิ่มมันไปยัง GameObject ที่สร้างในขั้นตอนที่ 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}`);
}
}
}
- สร้าง ZEPETOScript อีกอันและเขียน TestScript ด้านล่าง.
import { ZepetoScriptBehaviour } from 'ZEPETO.Script'
export default class TestScript extends ZepetoScriptBehaviour {
DoTest() {
console.log(`TestScript's DoTest() ถูกเรียกใช้งาน.`);
}
}
- ลากและเชื่อมต่อ TestScript กับ Inspector ของ Cube.
- คลิกที่ปุ่ม [▶︎(เล่น)] เพื่อสังเกตผลลัพธ์.
- คุณสามารถตรวจสอบความสำเร็จของการอ้างอิงวัตถุ, คอมโพเนนต์ Rigidbody, และคอมโพเนนต์ ZEPETOScript ในหน้าต่างบันทึกคอนโซล.
