Skip to content

[Unity] Let Objects Follow The Player Character

If you want to make objects that follow the player's movement in Unity, such as pets or coffins (?), then we can use List<Vector3> data type variables to store the player's moving route (that is the position that exists at each point in time). And keep the position of the object that you want to follow the player updated.


Example

I create two objects in scene for demo: player and pet. In order to make a distinction, I gave different colors.


Then we attach playerMove.cs script to player game object.

using System.Collections.Generic;
using UnityEngine;

public class playerMove : MonoBehaviour
{
    public GameObject petObject;
    public List<Vector3> positionList;
    public int distance = 20;
    public float speed = 0.1f;

    void FixedUpdate()
    {
        // Move
        if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += new Vector3(0, speed, 0);
        }

        if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.position += new Vector3(0, -speed, 0);
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.position += new Vector3(-speed, 0, 0);
        }

        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.position += new Vector3(speed, 0, 0);
        }

        // Pet following
        positionList.Add(transform.position);

        if (positionList.Count > distance)
        {
            positionList.RemoveAt(0);
            petObject.transform.position = positionList[0];
        }
    }
}




And don't forget to attach the pet object to the script of the player object in the Inspector in the Unity.


Finally, I recorded a video to see the effect of this object following the script.


References


Read More

Tags:

Leave a Reply