unity raycast 3d object code example
Example 1: raycast unity
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("No Hit");
}
Example 2: Unity Raycast
using UnityEngine;public class ExampleClass : MonoBehaviour
{
void FixedUpdate()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward); if (Physics.Raycast(transform.position, fwd, 10))
print("There is something in front of the object!");
}
}
Example 3: unity 3d raycast
using UnityEngine;
{
void FixedUpdate()
{
int layerMask = 1 << 8;
layerMask = ~layerMask; RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("Did not Hit");
}
}
}