How to make an object clickable depending on player distance?

I need to make an item in my scene clickable but only when the player is near the item. In my script I make the item in question go automatically to an empty GameObject that is child of my Player in the hierarchy to define the position but the click is able as soon as the camera have it framed. I'm using the character controller provided in the 2d physics and not a 2drigidbody so I'm even more confused because I can't use a collider.

In order to make anything clickable I would recommend IPointerXHandler interfaces (replace X with Click, Enter, Exit, Down, Up, etc).

Note:

Ensure an EventSystem exists in the Scene to allow click detection. For click detection on non-UI GameObjects, ensure a PhysicsRaycaster is attached to the Camera.

If you only want to click IPointerClickHandler is enough. If you want some visiual feedback like changing colors etc you'll have to expand it with at least IPointerEnterHandler and IPointerExitHandler.

public class MyClickable : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData pointerEventData)
    {
        ...
    }
}

Then in order to get the distance between two obects you can simply use Vector3.Distance e.g. with a ceratin threshold

// configure those e.g. in the Inspector
public float distanceThreshold;
public Transofrm playerTransform;
public Transform itemTransform;

and than use something like

if(Vector3.Distance(playerTransform.position, itemTransform.position) <= distanceThreshold)
{
    ...
}

so if you directly implement this into the MyClickable you could do visual feedback also in Update something like

public class MyClickable : MonoBehaviour, IPointerClickHandler
{
    public float distanceThreshold;
    public Transofrm playerTransform;

    // this gives you an event you can configure in the Inspector
    // exactly like you would with a button
    public UnityEvent onClick;

    private bool isInRange;

    public void OnPointerClick(PointerEventData pointerEventData)
    {
        // if too far away do nothing
        if(Vector3.Distance(playerTransform.position, transform.position) > distanceThreshold) return;

        ....

        onClick.Invoke();
    }

    private void Update()
    {
        if(Vector3.Distance(playerTransform.position, transform.position) <= distanceThreshold)
        {
            // e.g. make object green
        }
        else
        {
            // e.g. make object grey
        }
    }
}

How to make object clickable when Player object is in specific , For detecting distance between Box object(which i want to make clickable) and Player object I use empty object. So i want to make Box object� im making an RPG, and all is going quite ok, made a level system, gold etc, my problem now is i want to make quests, and the NPC's must only be 2-3 meters away to be clicked at, i know i shall use Vector3, and on mouse click, but i dont know how to do it, what comamnds to use, i checked out various sites, but this whole scripting thing is still very new to me, so if some kind sould could guide

I'm pretty sure you can have both a character controller and a collider on a gameobject (at least a trigger collider).

Then instead of whatever you're using to detect the click, you should use in an Update loop something like Input.GetKeyDown(KeyCode.Mouse0), and use a raycast where you can specify the length of the ray. https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

making objects clickable when 2 meters away, making objects clickable when 2 meters away here we check if the distance between our "Player" and the game object this script is attached� I have a grid made up of cubes. When the player hits move they move up/left/down/right to the next cube. Each cube has a trigger and various actions which happen. Due to the scale of my game i have loads of scripts running when i dont need to unless the player is close by. This will save alot on performance for mobile.

My suggestion is to use the onMouseDown() method. If you have a collider or trigger attached to your gameObject, onMouseDown() will detect mouse clicks on the object. Then in then body of onMouseDown() you can test if it is in range.

This is an example script how it could work:

public class ItemClickable : MonoBehaviour
{

    public Transform player;        // player-transform reference (depends if you have a singleton or not)
    public float range;             // radius (maybe you have a range or radius already set in your player instance)

    void Start()
    {
        // Setup for your references        
    }


    private void OnMouseDown()
    {   
        // Checks if the item is in the range of the player
        if ((player.position-gameObject.transform.position).magnitude < range) // Vector3.Distance() is also possible
        {
            Destroy(gameObject); // or do whatever you want in here
        }
    }
}

ClickDetector, They detect basic mouse events: enter, leave, left click and right click. ought not depend on all MouseHoverEnter events to fire a matching MouseHoverLeave event. Get an event that fires when a given property of an object changes. It also sets the maximum distance players can interact with the ClickDetector to 10 � GL has a function for this: gluUnproject() If you give that function the details of your view, along with the screen point being clicked on, it can tell you where in 3D space the user has clicked. If you check a point at both the near and far planes, the line between these points can be checked against your object.

Unity 2D: Detecting GameObject Clicks using Raycasts, Placing the click logic within the box's script in this case would require the box to have knowledge and access to the player, menu, and handles input events and delegates them to the objects being clicked. For our purposes, we'll perform a Raycast from the click location, with zero distance/direction. you can do this by using transparent elements above the button. when ok ist clicked, the transparent is gone (moves to side) and the button below will be clickable. This is our recommended way of doing this.

How To Draw A Line Between Two Points And Show Distance When , To make it possible to draw a line this gameobject should have line renderer Next game Duration: 3:46 Posted: 6 Aug 2019 Autoplay When autoplay is enabled, a suggested video will automatically play next. Up next Click Objects In Unity - How To Click Objects in Unity 5 | Unity Mouse Tutorial - Duration: 9:57.

this chooses the object that is within range and set the "distance to object" variable to the distance between it and the camera, the code works by focusing on only one object at a time sort of, because it needs to change the half size depending on the distance, in the level i had the 2 objects placed at 2 different places so that they don't

Comments
  • Thank you very much!!! I made it a little different because I'm using OnMouseDown and OnMouseUp... but your "if"logic with the distanceThreshold worked perfectly with what I already had so thanks for your time and help!!!
  • Thanks I knew of the existence of the docs. but as a total noob I find a little hard to search on it because I'm not sure where to find the things I'm looking for but I guess I'm going to give it a full check to become a little more familiar with the terms. Thanks for your time and suggestions!!!
  • I actually get to something very similar to your suggestion reading the answers above...maybe coming to read this before would make it faster hahaha thanks for your help and time I really appreciate it.
  • The problem with OnMouseDown() is it will only works for PC + Mouse, which can be inconveniant. In my project you can toggle VR and if I went for OnMouseDown() I would have needed to do everything differently to do the same thing. For the sake of portability I highly recommend my method.
  • @Jichael: But in the question the 2D aspect was mentioned, so I give the default way for doing this. And if you know you need an integration for VR of course the approach is a different one but this wasn't part of the question. The probability of making a coding mistake if you inexperienced with raycasting or the 3D-room and the transformation from the different spaces(even with the premade functions) is higher in my opinion.