Problems with using raycast to pick up an object

I have been working on a pickup script when you press E. I have put some debug.log’s and the first to if statements are successful but the third debug.log message doesn’t run. I haven’t been able to find the issue… Does anyone know what it may be?

using UnityEngine;


public class IngredientPickUp1 : MonoBehaviour
{

    public static bool IngredientOneCollected = false;


    void FixedUpdate()
    {
        RaycastHit hit;

        if (Input.GetKeyDown(KeyCode.E))
        {
            Debug.Log("first if successful");
            if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 10))
            {
                Debug.Log("second if successful");
                if (hit.collider.gameObject.tag == "IngredientOne")
                {
                    Debug.Log("third if succesful");
                    Destroy(gameObject);
                }
            }
        }        
    }



}

Did you tag fine your object ? Did the second debug work ?

I’m not sure what you mean, I think so though. On line 20 I’m pretty sure I checked if it had the right tag.

you have to be sure =) if your object is correctly tag in IngredientOne . You can see you raycast with
Debug.DrawLine(Vector3 origin, Vector3 dest , Color color);

then you have set your maximun distance to 10 . Try to use mathf.Infinity

What does Mathf.Infinity do?

it set the the value to infinity so when the ray cast hit something even from far you the hit is catch

But I want it so you can only pick it up from a certain distance

yes but if your second debug is never trigger something appen before

Obviously whatever object you’re hitting is not tagged as you expect. Print out the name and tag of the object you’re hitting to see what it is.

A common issue people run into with this kind of thing is hitting the player object itself.

How would I print the object name and tag? I did it awhile back but have forgotten. Would using a layer mask help so that the raycast doesn’t hit the player object?

            if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 10))
            {
                // Adding the gameObject parameter at the end of this call will also make the log message clickable to bring you to the object in the hierarchy.
                Debug.Log($"Raycast hit object: {hit.transform.name} with tag: {hit.transform.tag}", hit.transform.gameObject);

Yes if the layers are set up properly.

1 Like