Search code examples
c#unity-game-engineraycastinggameobject

Is there a method to compare the object hit by a raycast to another gameobject?


I am trying to produce a script that will check if the crosshair is pointing towards an interactive object and then when a key is pressed the object will move into a different position however I can't seem to find a function that doesn't bring up an error in my situation here is my current code:

public class Filingcabinetopen : MonoBehaviour {
    public GameObject draw;
    public GameObject Camera;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Physics.Raycast(Camera.transform.position, Vector3.forward, (float)2))
        {
            if (draw.Equals(RaycastHit.transform.gameObject))
            {
                // This is where my logic for the interaction will go but as of right now the selection statement doesn't work.
            }
        }


    }
}

I have almost no knowledge in c# it's my first time ever using it and i decided to take up a hard task so please help :)

I've tried using a few different methods but I can't seem to get the gameobject or tag from the object hit by the ray. Another example of what I have used is this:

if (Physics.Raycast(Camera.transform.position, Vector3.forward, (float)2))
        {
            RaycastHit RayObj;
            if (draw.Equals(RayObj))
            {
                //  
            }
        }

Solution

  • There is multiple way you can do that.

    1 : You can use Unity's layer system. - Tag the objects you want to be able to raycast to with a layer (On top right beside the tags)

    • Then use a layermask when you raycast

    LayerMask _myLayer = LayerMask.GetMask("the name of your layer");

    • Then specify the layerMask on your raycast

    if (Physics.Raycast(Camera.transform.position, Vector3.forward, (float)2), _myLayer)

    Or you can just get the name of the gameObject you just hit using hit.collider.gameObject.name (or tag or anything)