How to move an object in a unit? This example shows different ways to move.
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CharacterController))]
public class MovingAnObject : MonoBehaviour
{
[SerializeField] private int _speed;
private Rigidbody _rigidbody;
private CharacterController _characterController;
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
_characterController = GetComponent<CharacterController>();
}
private void Update()
{
// Call method here with one type of movement
// ...
}
private void MoveForward()
{
transform.position += Vector3.forward * _speed * Time.deltaTime;
// transform.position = Vector3.Lerp(transform.position, new Vector3(1, 1, 1), 3);
// transform.Translate(Vector3.forward * _speed * Time.deltaTime);
// _rigidbody.MovePosition(transform.position + Vector3.forward * _speed * Time.deltaTime);
// _characterController.Move(Vector3.forward * _speed * Time.deltaTime);
}
private void MoveSideways()
{
transform.position += (Vector3.forward + Vector3.right) * _speed * Time.deltaTime;
}
private void Jump()
{
_rigidbody.AddForce(Vector3.up * 200);
}
}
Transform.position
The world space position of the Transform. The position property of a GameObject’s Transform, which is accessible in the Unity Editor and through scripts. Alter this value to move a GameObject. Get this value to locate the GameObject in 3D world space.
Transform.Translate
Moves the transform in the direction and distance of translation. If relativeTo is left out or set to Space.Self the movement is applied relative to the transform’s local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo is Space.World the movement is applied relative to the world coordinate system.
Rigidbody
Moves the kinematic Rigidbody towards position. Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings. When Rigidbody interpolation is enabled, Rigidbody.MovePosition creates a smooth transition between frames. Unity moves a Rigidbody in each FixedUpdate call. The position occurs in world space. Teleporting a Rigidbody from one position to another uses Rigidbody.position instead of MovePosition.
CharacterController
Supplies the movement of a GameObject with an attached CharacterController component. The CharacterController.Move motion moves the GameObject in the given direction. The given direction requires absolute movement delta values. A collision constrains the Move from taking place. The return, CollisionFlags, indicates the direction of a collision: None, Sides, Above, and Below. CharacterController.Move does not use gravity.