Hi. I am trying to implement a for loop with a small delay between each iteration using coroutines, but for some reason can’t get it to work… The for loop inside the coroutine only happens once regardless of what I type in. What is the problem here?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Experience : MonoBehaviour
{
float speed = 3f;
public bool lockedOn = false;
bool hasReachedTarget = false;
public int expAmount = 1;
Action<GameObject> _killAction;
public List<Experience> experiencesInRange = new();
public GameObject target;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.CompareTag("Player"))
{
lockedOn = true;
target = collision.gameObject;
} else if (collision.CompareTag("Experience") && !lockedOn)
{
var exp = collision.GetComponent<Experience>();
if (exp.expAmount > 5) return;
if(expAmount <= 5)
{
experiencesInRange.Add(exp);
CheckExperience();
}
else
{
expAmount += exp.expAmount;
exp.target = gameObject;
exp.lockedOn = true;
}
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Experience"))
{
experiencesInRange.Remove(collision.GetComponent<Experience>());
}
}
private void OnDisable()
{
lockedOn = false;
speed = 3;
}
private void Update()
{
if (lockedOn)
{
if (target == null) target = GlobalData.player;
Vector2 direction = (target.transform.position - transform.position).normalized;
transform.position += (Vector3)direction * Time.deltaTime * 3 * speed;
speed += Time.deltaTime * 2;
if (Vector2.Distance(target.transform.position, transform.position) <= 0.3f)
{
if (target.CompareTag("Player") && !hasReachedTarget)
{
StartCoroutine(GetExp(expAmount));
_killAction(gameObject);
} else if (target.CompareTag("Experience"))
{
Destroy(gameObject);
}
}
}
}
public void Init(Action<GameObject> killAction)
{
_killAction = killAction;
}
void CheckExperience()
{
int totalExp = expAmount;
foreach(Experience exp in experiencesInRange)
{
totalExp += exp.expAmount;
}
if(totalExp > 5)
{
GetComponent<SpriteRenderer>().color = Color.red;
expAmount = totalExp;
for(int i = 0; i < experiencesInRange.Count; i++)
{
experiencesInRange*.target = gameObject;*
experiencesInRange*.lockedOn = true;*
}
experiencesInRange.Clear();
}
}
IEnumerator GetExp(int expAmount)
{
hasReachedTarget = true;
for (int i = 0; i<expAmount; i++)
{
Debug.Log(“One experience”);
target.GetComponent().Exp++;
yield return new WaitForSeconds(.001f);
}
Destroy(gameObject);
}
}