[Help] Distance Limit for Player Open Door

Hello, I created a door open/close script and what that script does is when my cursor is on the door i can open the door with holding down left mouse button and moving left and right the mouse. The script works fine but i have one problem. I can open the door from miles away as long as my cursor is on the door. How can i put a limit of how far the player can be in order to open the door? I tried this script on my player but it doesn’t work. Any help?

using UnityEngine;
using System.Collections;

public class PlayerRaycast : MonoBehaviour {

    public float interactDistance = 5f;
    public float canOpenDoor = 0;

    void Update () {

        Ray ray = new Ray (transform.position, transform.forward);
        RaycastHit hit;
        if (Physics.Raycast (ray, out hit, interactDistance)) {
         
            if (hit.collider.CompareTag ("Door")) {
             
                canOpenDoor = 1;
            } else {
                canOpenDoor = 0;
            }
        }
    }
}

and then i used this if statement in my door script but it didn’t work, i got a null reference error.

if (GetComponent<PlayerRaycast> ().canOpenDoor == 1) {
            //door open script
        }

So you have PlayerRaycast on your player, but you have that second script on your door?

correct, my idea was to create a raycast starting from player position to x amount of meters forward and check if it hits any door then i can use my door script.

Your second script is on your door, which means when it tries to reference itself to get the PlayerRaycast script, it can’t find it. That is why you’ll get a null reference error.

You’ll have to have a reference to the player and use getComponent to get the script from your player and check it’s value.

I tried that in my door script but i get an error saying “A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.GetComponent(System.Type)'”

PlayerRaycast PlayerRaycast = GetComponent<PlayerRaycast>();

if (PlayerRaycast.canOpenDoor) {
            //script
        }

Don’t name your variable the same as your class. Plus, you’re still doing the same check. GetComponent checks the object the script is on for what you’re looking for, which means it’s still looking at your door trying to find PlayerRaycast.

If you’re doing PlayerRaycast playerRaycast = GameObject.Find(“Player”).GetComponent();

Then you can check the value of the variable on playerRaycast. Note, this only works if your gameobject is named Player, but it’s just one example of how you can do it.

Thank you for the help, I found the correct way to do it from another guy but you helped me too.

public PlayerRaycast playerRaycast;

void Start() {
    playerRaycast = GameObject.Find("ObjectName").GetComponent<PlayerRaycast>();
}