unity block raycast code example
Example 1: unity raycast
void Update()
{
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");
}
}
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 ui block physics raycast
private bool IsOverUI(TouchState touch)
{
PointerEventData pointerData = new PointerEventData(EventSystem.current);
pointerData.position = touch.position;
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);
if (results.Count > 0)
{
for (int i = 0; i < results.Count; i++)
{
if (results[i].gameObject.GetComponent<CanvasRenderer>())
{
return true;
}
}
}
return false;
}