Dinu Adrian
Dinu Adrian

Reputation: 139

I am using Raycast in unity and i want to get the position of an object when i click on it but i does not work and i don't know what i am doing wrong

So when I am clicking on the object in the game I get this error...

NullReferenceExceptionm : Object reference not set to an instance of an object JumpDestination.Update () (at Assets/Scripts/JumpDestination.cs.:12)

I don't know what I am doing wrong,how can I fix it? I want to get the position of the hited object.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JumpDestination : MonoBehaviour {

    private RaycastHit hit;
    public float jumpMaxDistance;

    void Update(){
        Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, jumpMaxDistance);
        if (hit.collider.gameObject.tag == "RichPoint") {
            print (hit.collider.transform.position);
        }
    }
}

Upvotes: 0

Views: 1628

Answers (1)

Programmer
Programmer

Reputation: 125455

I don't know what I am doing wrong,how can I fix it? I want to get the position of the hited object.

3 things you did wrong:

1.You did not check if mouse is pressed before raycasting.

2.You did not check if Physics.Raycast hit anything before printing the object's position.

3.You defined the hit variable outside a function. Not a good idea because it will still store the old object the mouse hit. Declare that in the update function.

FIX:

void Update()
{
    //Check if mouse is clicked
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;

        //Get ray from mouse postion
        Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition);

        //Raycast and check if any object is hit
        if (Physics.Raycast(rayCast, out hit, jumpMaxDistance))
        {
            //Check which tag is hit
            if (hit.collider.CompareTag("RichPoint"))
            {
                print(hit.collider.transform.position);
            }
        }
    }
}

Regardless, this answer was made to show you what you did wrong. You should not be using this. Use Unity's new EventSystems for this. Check the 5.For 3D Object (Mesh Renderer/any 3D Collider) from this answer for proper way to detect clicked object.

Upvotes: 1

Related Questions