I’m trying to make a game where objects can be collected (via a trigger) and will join a line of identical objects to make a conga line.
Obviously each object should be following the one directly in front of it, so my idea was to use an array so it could identify which object within that array should be followed, based on how many are already following the player, which is why I’m using a static variable so they can all keep track of how many are currently following.
However, what I have now isn’t working. It says ‘Object reference not set to an instance of an object’. Am I using arrays wrong?
using System.Collections;
using UnityEngine;
public class FollowerScript : MonoBehaviour
{
bool isActive = true;
static int followerAmount = 0;
public GameObject playerRabbit;
GameObject followTarget;
float DistanceFromTarget;
Animator animator;
void Start()
{
animator.GetComponent<Animator>();
}
void FixedUpdate()
{
//Rabbit will only follow if it has been activated.
if (isActive)
{
FollowTheTarget();
}
}
//When the player moves close to the follower it will activate.
private void OnTriggerEnter(Collider other)
{
//Array contains all the followers and the player character.
GameObject[] Rabbits = GameObject.FindGameObjectsWithTag("Rabbit");
playerRabbit = Rabbits[0];
// If the collided object is the player and the follower has not already been activated.
if (other == playerRabbit && !isActive)
{
//Default follower amount is zero, the player.
followTarget = Rabbits[followerAmount];
isActive = true;
followerAmount++;
}
}
void FollowTheTarget()
{
//Makes the followers stop a certain distance from the target.
DistanceFromTarget = Vector3.Distance(transform.position, followTarget.transform.position);
if (DistanceFromTarget > 2)
{
//Moves the follower towards the target + animations.
transform.position = Vector3.MoveTowards(transform.position, followTarget.transform.position, 0.3f);
animator.SetBool("IsRunning", true);
transform.LookAt(followTarget.transform);
}
else
{
animator.SetBool("IsRunning", false);
}
}
}