Studio GuideWorld SDK Guide
Log In

Raycast

The Raycast function can be used for efficiently finding an Object within a scene in Unity.

Raycast in Unity programming is a kind of laser beam, which will shoot from a location in a scene and shoot until it hits a Collider.

When it collides a Collider, the information(RaycastHit) of the collided Object and position within the scene will be returned.

For more details on Unity Raycast, please review the Unity guide.

📘

Unity Raycast

https://docs.unity3d.com/Manual/CameraRays.html


The Unity Raycast can be used in ZEPETO.Script by completing the following steps:

First, import the Raycast related class.

import { Physics, RaycastHit } from 'UnityEngine';

The following is an example code for the Raycast function:

import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
import { Physics, RaycastHit, Input, Camera } from 'UnityEngine';
 
export default class RaycastSample extends ZepetoScriptBehaviour {
 
    Update() {
        this.MouseControl();
    }
      
    MouseControl() {
        if (Input.GetMouseButtonDown(0)) {
            let ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      
            // Please note that In order to retain the RaycastHit information as an output parameter it must be wrapped in a $ref tag.
            // Because we require the out qualifier as a parameter, we create a reference without actually creating an object.        
            let ref = $ref<RaycastHit>();
      
            if (Physics.Raycast(ray, ref, 1000)) {
                // To check the returned Raycast hit data, please remember to unwrap the reference by using $unref
                let hitInfo = $unref(ref);
      
                console.log(`Detect Hit!`);
                console.log(`hitInfo.collider.name : ${hitInfo.collider.name}`);
            } else {
                console.log(`Failed to Detect Collision`);
            }
        }
    }
 
}

📘

Please refer to the following guide for explanations of the $ref and $unref used in the script. [$ref & $unref]


Through the test code, you can check that the information of the object is output by clicking the Cube with the mouse pointer in the Scene.


Find more information for the Raycast API used in the ZEPETO.Script by going to the link below.



📘

Raycast

https://docs.unity3d.com/ScriptReference/Physics.Raycast.html