OnMouseDown within certain distance?

Right now I am using OnMouseDown() to make some things happen, but is there a way to do this where the user (first person controller) has to be within a certain distance in order for this to work?

I am still very new to C# and to Unity, so if you could be as specific as possible, it would be greatly appreciated. Thank you!

if ((transform.position - player.position).magnitude < requiredDistance)
{
    DoGreatThings();
}
1 Like

Super new to this, so bear with me. It’s not recognizing a “player” name, I imagine that’s probably an issue with the way I have my FPC set up?

Also, for required distance - what is that based on? I just put in an arbitrary number, but I’m not sure how the scale works.

using UnityEngine;
using System.Collections;
public class Serial1 : MonoBehaviour {
    [SerializeField]
    private SerialDoer Dd;
   
    void OnMouseDown () {
        if ((transform.position - player.position).magnitude < 3) {
                        Dd.Switch (true);
                }
        }
   
}

You need to declare player somewhere. I don’t know what you’re using so I just left it ambiguous.

Distance is measured in “units” which can be whatever you want them to be (within limitations of the physics engine). The typical starting point (and the one we still use) is one unit is one meter. So your code would fire if the player was 3 meters from the thing.

1 Like

What would that look like in the code?

I have no idea what you’re using or what you’re trying to do honestly, so I can’t answer that.

I have a First Person Controller, and the script works when you click on the object where the script is applied, I’m just not sure how to call it in the script. So sorry, I’m a total dolt when it comes to scripting. >.<

There are a lot of different ways. The easiest one (if not the most efficient) is to create a variable called player and assign it via the Inspector

public class Serial1 : MonoBehaviour
{
    [SerializeField()]
    Transform player;

    void OnMouseDown() {.....}
}
1 Like

Got it working now, thank you so much for your help!