I’m having trouble getting a raycast to work. I attach the following script to a cube object. The ray it creates intersects the bounds of the cube. The bounds of the collider detects the ray’s intersection, but the collider itself doesn’t register a hit when raycasted. What might cause the raycast to return false?
using UnityEngine;
using System.Collections;
public class RaycastTest : MonoBehaviour {
// Update is called once per frame
void Update () {
// Make a ray that definitely intersects our box collider
Ray ray = new Ray(gameObject.collider.bounds.center, Vector3.one);
Debug.DrawLine (ray.origin, ray.origin + ray.direction, Color.red);
// Cast the ray three different ways, expecting all to return true;
RaycastHit hitInfo;
bool hitBounds = gameObject.collider.bounds.IntersectRay(ray);
bool hitCollider = gameObject.collider.Raycast(ray, out hitInfo, ray.direction.magnitude);
bool hitAnyCollider = Physics.Raycast(ray, out hitInfo);
// Expecting all hits to be true always
Debug.Log (ray.ToString () + hitBounds.ToString () + hitCollider.ToString () + hitAnyCollider.ToString ());
// hitBounds is always true.
// hitCollider and hitAnyCollider are always false. Why?
}
}
The box collider’s IsTrigger=false.
The cube is not on the IgnoreRaycast layer.