- Home /
Problem is not reproducible or outdated
Why doesn't my prefab go to the closest enemy?
So I'm making a chain hit spell which is suppose to bounce to enemies close by the one I orginally hit. So how come my prefab doesn't work? I used the following code:
public class ChainHit : MonoBehaviour
{
//this is for prefab
[SerializeField]
public LayerMask layerMask;
private List<Transform> targets = new List<Transform>();
public int damage;
public Transform MyTarget { get; private set; }
private int targetIndex;
protected bool hit = false;
protected void OnTriggerEnter2D(Collider2D other)
{
MyTarget = other.transform;
Debug.Log("Test1");
if (!hit && other.tag == "EnemyBase")
{
hit = true;
Collider2D[] tmp = Physics2D.OverlapCircleAll(other.transform.position, 10, layerMask);
Debug.Log("Test2");
foreach (Collider2D collider in tmp)
{
if (collider.transform != MyTarget && collider.transform != MyTarget && collider.transform != transform && collider.tag == "EnemyBase")
{
targets.Add(collider.transform);
}
}
PickTarget(other);
}
}
private void Update()
{
float distance = 0;
if (MyTarget != null)
{
distance = Vector2.Distance(transform.position, MyTarget.position);
}
if (distance <= 0.1f)
{
if (hit && targetIndex < targets.Count)
{
PickTarget(MyTarget.GetComponent<Collider2D>());
Debug.Log("Test3");
}
else if (MyTarget != null)
{
//add damage routine here
}
}
}
private void PickTarget(Collider2D collision)
{
Enemy enemyScript = collision.GetComponentInParent<Enemy>();
enemyScript.enemyHealth -= damage;
MyTarget = targets[targetIndex];
targetIndex++;
}
}
Now as you may see I have Debug 1,2,3. 1 is always triggered when it enters an enemys collider, even if it doesn't deal damage to it and just passing through (for some reason). 2 also triggers just fine and only on the first target hit, which is still normal so I know the code works that far. However 3 is never triggered in the code. So does anybody know what I'm doing wrong and how to fix the issue? I'm using this tutorial and it works fine there.
Follow this Question
Related Questions
My chain hit goes to the center of the map, why? 0 Answers
Distribute terrain in zones 3 Answers
Projectile isn't reaching my target. 1 Answer
help with making enemy projectile fly at player at one speed 0 Answers
Multiple Cars not working 1 Answer