Updating GameObject Position in Unity 5

I have a simple Sprite called Player that has the follow components (Transform, Sprite Renderer, Box Collider 2D, Rigidbody 2D, Player Controller Script). In my Player Controller script I want to update the player's position when a key is pressed.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

Vector2 playerPos;

// Use this for initialization
void Start () {

playerPos = gameObject.transform.position;

}

// Update is called once per frame
void FixedUpdate () {

if (Input.GetKey("d")) {

playerPos = new Vector2(playerPos.x + 0.2f, playerPos.y);

}

}
}


This script is attached to my gameobject but whenever I press or hold down the 'd' key, nothing happens to the player. Does anyone know how to fix this?

Vector2 is a C# struct, which is a value type. That means when you assign a Vector2 to a variable, or pass it as an argument/return value, you're copying the value of the Vector2 — not passing around a reference to it.

So when you say

playerPos = gameObject.transform.position;

You are copying the player's current position into playerPos

(You can skip the gameObject at the front, since the MonoBehaviour's transform getter does the same thing)

Everything you do after that is just modifying this copy — you never assign it back to the player transform to actually move the player.

If you want to move the player to the new location, you need to assign the value back to the player's transform:

transform.position = playerPos;

• Thanks! This was the clarification that I was looking for. I'll probably have to look more into structs and the C# language. – Rowen McDaniel Jun 9 '16 at 0:44

You want something like:

var player = GameObject.Find("Player");

Then

player.transform.position = new Vector2(playerPos.x + 0.2f, playerPos.y)

Describes: Moving in one direction continuously and then move the opposite direction continuously when you press a button.

• Thanks for the suggestion, I also wanted to know if it is possible to directly add to the game objects position rather than using it's rigidbody. – Rowen McDaniel Jun 9 '16 at 0:35