using UnityEngine; public class MoveObject : MonoBehaviour { private Rigidbody2D rb; void Start() { rb = GetComponent(); } void Update() { rb.velocity = new Vector2(1f, 0f); } }
using UnityEngine; public class PlayerController : MonoBehaviour { public float speed = 5f; private Rigidbody2D rb; private void Awake() { rb = GetComponentIn this example, the PlayerController script is attached to a game object with a Rigidbody2D component. In the Unity editor, the speed variable is set to 5. The Awake method retrieves a reference to the Rigidbody2D component using the GetComponent method and assigns it to the rb variable. In the Update method, the player's movement is determined using the Input.GetAxis method, and a force is applied to the Rigidbody2D component using the AddForce method.(); } void Update() { float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); Vector2 movement = new Vector2(moveHorizontal, moveVertical); rb.AddForce(movement * speed); } }