Important: I took parts of the code from here but the OP did not get a helpful answer yet
Make an AI move to a collectable, call a method and fly back in Unity
I have a follower which is following the player. This follower has a trigger attached. This trigger scans the area and looks for gems to collect. When collecting a gem, the follower should move to it, activate some code of the gem and move back to the player.
The default state
The collectable entered the trigger zone
So I tried to achieve it by using Enumerators. When the follower is not collecting gems, it should follow the player.
When I start the game and move to a gem, the follower is not moving to the gem but the gem does fine. It moves to the player. But the follower does not move.
So my improved code looks this
private Transform player;
private List<Collectable> collectablesToCollect = new List<Collectable>(); // all items found in the area
private bool isCollecting = false;
private float movementSpeed = 10;
private void Start()
{
player = Globals.GetPlayerObject().transform; // find the player object in the scene
}
private void Update()
{
if (CollectablesInRange()) // any gems in the area?
{
if (!isCollecting)
MoveToCollectable(); // Collect the gem
}
else
{
FollowPlayer();
}
}
private void OnTriggerEnter(Collider col)
{
Collectable collectable = col.GetComponent<Collectable>();
if (collectable != null) // is the found object a gem?
{
if (!collectable.GetMovementState()) // got it collected?
collectablesToCollect.Add(collectable);
}
}
private void OnTriggerExit(Collider col)
{
Collectable collectable = col.GetComponent<Collectable>();
if (collectable != null)
collectablesToCollect.Remove(collectable); // remove it from the list of items to collect
}
private void MoveToCollectable()
{
isCollecting = true;
Collectable collectable = collectablesToCollect.First(); // get the first gem in the list
Vector3 defaultPosition = transform.position;
CollectionMovement(transform.position, collectable.GetCollectablePosition()); // move to the gem
collectable.StartMovingToPlayer(); // activate the gem
CollectionMovement(transform.position, defaultPosition); // move back to the default position
collectablesToCollect.Remove(collectable); // remove the gem from the list
isCollecting = false;
if (CollectablesInRange()) // are there more gems to collect?
MoveToCollectable();
}
private IEnumerator CollectionMovement(Vector3 startPos, Vector3 endPos)
{
transform.position = Vector3.MoveTowards(startPos, endPos, movementSpeed * Time.deltaTime);
yield return null;
}
void FollowPlayer()
{
Vector3 playerPos = player.position;
transform.position = new Vector3(playerPos.x, playerPos.y + 2, playerPos.z);
}
private bool CollectablesInRange() // any gems in the area?
{
return collectablesToCollect.Count > 0;
}
Really important should be the part when it comes to IEnumerator CollectionMovement()
and the call in MoveToCollectable()