Search Unity

Player object position won't update?

Discussion in '2D' started by theo9743, Feb 23, 2020.

  1. theo9743

    theo9743

    Joined:
    Feb 18, 2020
    Posts:
    12
    Hi guys, I have a slight issue. I have a very basic script which is just being used to determine the current distance between the player and the enemy. The transform is linked to the player object. However when I run the code, it keeps the player.position at it's starting value (wherever it's been placed beforehand) and It doesn't update even if the player moves? Anyone know why?

    Thanks


    public Transform player;

    void Update()
    {
    Vector3 direction = player.position - transform.position;
    Debug.Log(direction);
    }
     
  2. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,799
    You are not changing transform.position to something, you’re just calculating a direction Vector and then doing nothing with it.
     
  3. theo9743

    theo9743

    Joined:
    Feb 18, 2020
    Posts:
    12
    Shouldn't the direction Vector change it's value after each Update() though?
     
  4. theo9743

    theo9743

    Joined:
    Feb 18, 2020
    Posts:
    12
    The code works if I just place a player and enemy object on the area with the scene manager, but it only stops working if I turn the player into a prefab
     
  5. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,799
    It should, is "player" correctly set in the inspector? (you can also check during runtime if it points to the right object)
     
  6. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    When you make a prefab, you may want to consider doing this:

    Code (CSharp):
    1. private GameObject player;
    2. private Transform playerTransform;
    3. private Vector3 direction;
    4. void Start()
    5. {
    6. player = GameObject.FindWithTag("Player");
    7. }
    8.  
    9. void Update()
    10. {
    11. playerTransform = player.transform.position;
    12. direction = playerTransform - transform.position;
    13. }