Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Cannot figure out Vector2

Discussion in 'Scripting' started by RogueEclips3, Feb 14, 2020.

  1. RogueEclips3

    RogueEclips3

    Joined:
    Feb 6, 2020
    Posts:
    4
    So I am creating a script for my game, and I need to create a Vector2 to do something with my player position. I created a game object called playerObject, which is the player (obviously). I also created the Vector2 called playerPos and set it to playerObject.transform.position. I get an error saying this:

    Assets\Scripts\Inventory.cs(12,32): error CS0236: A field initializer cannot reference the non-static field, method, or property 'Inventory.playerObject'

    Code (CSharp):
    1.     public GameObject playerObject;
    2.     public Vector2 playerPos = playerObject.transform.position;
    Can someone please help me?
    EDIT: It's flagging the "playerObject" in the Vector2 line.
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,386
    You can only assign a value to variable inside of a method, try assigning the value in the Start method.

    Edit: or actually, you can assign simple value literals (such as
    float x = 0f;
    ) but something like
    playerObject.transform.position;
    cannot be done outside of a method because it requires some runtime processing. Like I said, though- just put the assignment in the Start method and it should work.
     
    Last edited: Feb 14, 2020
    Ryiah likes this.
  3. sbalanoff

    sbalanoff

    Joined:
    Nov 14, 2019
    Posts:
    36
    If you are using Vector2s for a 2D game in this case you must use a Vector3.
     
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    Vector2 and Vector3 are implicitly convertible between each other. You don't have to use a Vector3 to store the position of the object if you only care about the X and Y coordinates. That said it is possible for the conversion to be ambiguous and confuse the compiler. In that case you need to manually tell it which way you intended.
     
  5. RogueEclips3

    RogueEclips3

    Joined:
    Feb 6, 2020
    Posts:
    4
    Thank you guys so much. It worked! I had to but the Vector2 in Update() because this is an inventory script, and I had to include dropping, so whenever you dropped an item it would appear at the Player.