- Home /
Making objects follow each other in a line, and objects ignoring minimum follow distance.
I'm trying to make a group of objects follow each other in a kind of conga line as they are collected by the player. The idea is that each object will set itself as the last object in the current line so that the next object knows who to follow. However, the following script has 2 problems.
The objects do not follow each other in order, rather they only follow the player. I assume this is some sort of error with the static array and it's not being updated across all the other instances of the code, but I don't know how to fix it.
The objects are ignoring the minimum distance at which they should stop moving towards the player. They continue to move into and push the player, which is odd because this same movement code worked before I started adding the array to make the conga line.
Would appreciate any help thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewFollowCode : MonoBehaviour
{
public Transform thisRabbit;
public Transform player;
bool IsActive = false;
float speed = 1.0f;
const float minDistance = 2f;
Vector3 DistancefromTarget;
Animator m_Animator;
public Transform target;
public static Transform[] followers;
public static int followerCount = 0;
void Start()
{
followers[0] = player;
m_Animator = GetComponent<Animator>();
}
private void OnTriggerEnter(Collider other)
{
if (other.transform == player)
{
IsActive = true;
target = followers[followerCount];
followerCount++;
followers[followerCount] = thisRabbit;
}
}
void FixedUpdate()
{
if (IsActive)
{
Follow();
}
DistancefromTarget = transform.position - player.position;
}
void Follow()
{
transform.LookAt(player);
if (DistancefromTarget.magnitude > minDistance)
{
transform.Translate(0.0f, 0.0f, speed * Time.deltaTime);
}
}
}
Answer by unity_PkeTMQ-bDf-2XQ · May 28, 2020 at 01:27 AM
Good News! I was able to fix the second problem. All I had to do was change void FixedUpdate to LateUpdate, and move the DistancefromTarget calculation from there to void FixedUpdate.
Like so.
private void FixedUpdate()
{
DistancefromTarget = transform.position - player.position;
}
void LateUpdate()
{
if (IsActive)
{
Follow();
}
}
Answer by Bangurah · Nov 25, 2020 at 06:22 AM
Did you attach the script to the player or objects?
Also, the script keeps giving me NullException Errors for when: followers[0] = player;
Your answer
![](https://koobas.hobune.stream/wayback/20220612235404im_/https://answers.unity.com/themes/thub/images/avi.jpg)