Unity doesn't recognize raycast collision

I’m trying to get an interaction system done in Unity for my project using raycast to measure the distance between player and object to interact with. Using both DrawLine and DrawRay it looks like the raycast collide with the object, but the conditions are not reached


there are 3 scripts:
Player script

public class PlayerInteraction : MonoBehaviour
{
    public float interactionRange;
    public GameObject interactionUI;
    public TextMeshProUGUI interactionText;

    
    private void Update()
    {
        InteractionRay();
    }

    void InteractionRay()
    {
        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        bool hitSomething = false;

        if(Physics.Raycast(ray, out hit, interactionRange))
        {
            Iinteractable interactable = hit.collider.GetComponent<Iinteractable>();

            if (interactable != null) {
                hitSomething = true;
                interactionText.text = interactable.GetDescription();

                if(Input.GetKeyDown(KeyCode.N))
                {
                    interactable.Interact();
                }
            }
        }
        interactionUI.SetActive(hitSomething);
        //Debug.DrawRay(ray.origin,interactionRange* ray.direction, Color.green);
        Debug.DrawLine(ray.origin, hit.point, Color.red);
    }

}

interface script

public interface Iinteractable {
    void Interact();
    string GetDescription();
}

object script:

public class Test : MonoBehaviour, Iinteractable
{

    public string GetDescription()
    {
        return "Press";
    }

    public void Interact()
    {
        Debug.Log("Did Hit");
    }
}

Your raycast is probably colliding with the player. Make sure it ignores the player layer.

1 Like

i excluded the collision with player’s layer from the character controller and made sure the obstacle is on another layer

Okay but your code doesn’t seem to do that at all.

so this is what i’ve done

LayerMask mask = LayerMask.GetMask("Water");


        if(Physics.Raycast(ray, out hit, interactionRange, mask))

i assigned player’s layer to water but it still doesn’t work


using the drawline method, it doesn’t move from the center of the plane. i tried to assign plane’s layer to water too, but still doesn’t move.
if i’m going with drawray method, it shows correctly and goes through the cube

Your mask only hits water, your logic is inverted.

Presumably the issue was that your target object didn’t have an Iinteractable component on it. Do some more debugging to figure out whether the object you’re interacting with is what you expect, and what the outcome of your if statements are.

1 Like

oh thank you, i thought the layer assigned in the code is the one to avoid collision with. Thank you very much!