Search Unity

[SOLVED - Basic Resolution] Vector3.Distance Only Calculating Player Spawn / Start Position

Discussion in 'Editor & General Support' started by OrbitamiEntertainment, Feb 16, 2019.

  1. OrbitamiEntertainment

    OrbitamiEntertainment

    Joined:
    Dec 21, 2016
    Posts:
    4
    Hey, everyone. I just wanted to take a moment here and throw something out there for the other independent / freelance developers like myself. I noticed a common question on the forums in regards to this problem. I at one point had a similar issue.

    The player and enemy were not spawned in my case. They were already "plopped" into the scene, but they are saved as prefabs. When using the Vector3.Distance(targe.position, transform.position) code, it was only returning the player's position from the start of the game. The code was being used as follows:

    // This code is attached to the enemy
    void Update()
    {
    float separationDistance = Vector3.Distance( Vector3.Distance(target.position, transform.position);
    Debug.Log("Separation Distance: " + separationDistance); // This to track the value live during runtime
    }

    The value for separationDistance was being calculated, but only with the enemy's (dynamic / changing) and players ( static / not changing) positions. This didn't make sense because the characters position was changing during runtime as the player moved around the scene. The resolution was to create a GameObject in the start function of the enemy script, and a reference to the player prefab. Then assign the player transform to the player prefab reference.

    private Transform playerPrefab;

    void Start()
    {
    GameObject playerTransform = GameObject.FindGameObjectWithTag ( "Player" );
    playerPrefab = playerTransform.transform;
    }

    It's to my understanding that when an enemy object is spawned, and is a clone, that the clone will have to be informed of any new player instances. In this case, neither were clones and the issue seemed to be the actual timing of the game frames. The enemy was "spotting" the player at the start of the game but possibly not the instance of the game object. Once doing this, the Vector3.Distance calculations were now correct in either situation. If anyone has more insight, and / or wants to further this topic, please feel free. I am also open to being corrected. Have a great day to those who have read this, and I hope it has helped somewhat!