Search Unity

Question How do I get the players position as a Vector2 in a script

Discussion in 'Getting Started' started by nimmi1, Aug 28, 2023.

  1. nimmi1

    nimmi1

    Joined:
    Aug 28, 2023
    Posts:
    7
    I need to get the player's position as Vector2 destination
     

    Attached Files:

  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    I'm pretty sure the code that you posted there should work because I think a Vector3 can implicitly cast to a Vector2. If you are getting an error message than try (Vector2)transform.position.
     
  3. nimmi1

    nimmi1

    Joined:
    Aug 28, 2023
    Posts:
    7
    The code works, i just have to be able to assign the players position as the Vector2 destination
     
  4. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    destination = transform.position;

    should just work, I would think.
    If not,
    destination = (Vector2)transform.position;


    The first code snippet is an "implicit cast" which means that C# automatically converts one to other without you having to say anything.

    The second code snippet is an "explicit cast" which means C# knows how to convert from type to another, but you have to explicitly tell it to.

    I think the implicit case should work, though.
     
  5. nimmi1

    nimmi1

    Joined:
    Aug 28, 2023
    Posts:
    7
    the script I posted is for moving an enemy that is supposed to always run after the player at a fixed speed, I need it to know where the player is for it to be able to move towards the player
     
  6. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    Oh, I thought that was the player script.
    Well, you just need to get a reference to the player.

    You could just add a public variable
    public Transform playerTransform;

    or something like that.

    Then you should see a slot in the inspector that you can drag the player into.
     
  7. nimmi1

    nimmi1

    Joined:
    Aug 28, 2023
    Posts:
    7
    where exactly do i need to add that, sry im really new to programming
     
  8. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    There's already one public variable in your code. Add it to the same place.
     
  9. nimmi1

    nimmi1

    Joined:
    Aug 28, 2023
    Posts:
    7
    ok thx it works