Vector3.distance wrong distance calculating?

I have Player object and Enemy object. Enemy is always stalking Player and trying to kill him. In function that sends damage to Player i use Vector3.distance to calculate disance between two objects and here strange things begin to appear: If i move Enemy prefab from editor to scene manually everything works fine, distance calculates correctly and Enemy sends damage to Player as it comes close enough. But if I Instatiate the same Enemy prefab via script Vector3.Distance begins to calculate the distance from the Enemy to some point located at the other end of the map, where there is literally nothing. There are no objects with the same tag (Im referencing Player GameObject to Enemy using FindGameObjectWithTag). Because of that Enemy can’t hit Player.

Interestingly, to calculate the movement of the enemy to the player, I use the function Vector3.MoveTowardswith the same referencing to Player GameObject and it works fine in both cases.

i.e. if Enemy was Instatiated via script, it can move to Player but cannot hit him because the distance is calculated incorrectly

I ask you not to say that the FindGameObjectWithTag operation is heavy and “costs” some computing power, I know it

Reference for Vector3.Distance():

void Start()
{
Target = GameObject.FindGameObjectWithTag("Player");
}
Vector3.Distance(Target.transform.position, transform.position)

Reference for Vector3.MoveTowards():

void Start()
{
Target = GameObject.FindGameObjectWithTag("Player");
}
Vector3.MoveTowards(transform.position, new Vector3(Target.transform.position.x, transform.position.y, transform.position.z), speed * Time.deltaTime);

Game is in 2D space

Well you most likely do not have your objects placed on the same z depth. In your moveTowards method you do not move towards the player / target but towards the player / target position projected onto the depth plane where this object is located.

Vector3.Distance calculates just the euclidean distance in 3d. There certainly is nothing wrong with it. If something doesn’t turn out as you expected it’s your fault. Probably because your input positions are not what you think they are. Have you actually started debugging your issue? Have you printed the two positions? What distance do you get? Have you printed it?

Bunny83 said

Vector3.Distance calculates just the
euclidean distance in 3d.

Since my game is in 2D space, I immediately went to check the Z coordinate, and the problem was there. Spawner that spawns Enemy prefabs was at -60 Z coordinate, and passed its coordinates to the instatiated objects.