Determine distance to player from prefab

I am trying to make is so my player can only interact with a prefab if it is within a certain distance. I have tried several ways. When I try to set it manually by using a public variable, the data is lost when I save the new prefab and when I use:

float dist = Vector3.Distance(GameObject.FindGameObjectsWithTag("Player").position, transform.position);
            Debug.Log("Distance to other: " + dist);
            if (dist < 1)
            {

It just does not work… I am not sure how to set my player as the variable at run time… thank you for your help.

GameObject.FindGameObjectsWithTag(“Player”).position this returns a GameObject array so you cant access a position variable. if you do it like this: GameObject.FindGameObjectWithTag(“Player”).transform.position, it should work.
Difference is Object not ObjectS and you put the .transform after it.

GameObject means an array (or list) of GameObjects; the means which one in that array (or list) you want to select (0 being the first element), so for example:

  1. I have 10 enemies in a scene, I store all those in an array (or list) like this (array example here):

    GameObject[] enemies = new GameObject[10];
    
  2. In this example, I made an array variable of the 10 enmies into the ‘enemies’ variable; now lets say I want to access enemy 4, I would type something like this:

    enemies[3].transform.positoin
    

To get the fourth enemy’s position (remember, in lists and arrays, 0 is the first element).


I hope my example of arrays and lists helped you understand the logic behind them moving forward; this example the OP is trying to measure the distance from an enemy to the Player, is that what you want? If so, this video has a great explanation on how to find the closest enemy to a player (and you can use this tutorial to do other things once you understand how to calculate distance between a list of objects and one singular object), and would direct you there to get a better understanding.


Now let’s say you do in fact want to find just one GameObject, and not a list or array and you are getting that error looking for GameObject, then instead of this code:

GameObject.FindObjectsWithTag("Whatever").transform

make sure it isn’t FindObjects, but this:

GameObject.FindObjectWithTag("Whatever").transform

And that will return the first instance of “whatever”; so if there is only one in a scene, it will return only that one and will work for you.