Home > OS >  error CS0103: The name 'hitEnemies' does not exist in the current context
error CS0103: The name 'hitEnemies' does not exist in the current context

Time:11-28

i am new with coding. i just trying a to code a small game and there seems to be a bug i cant fix. can someone help me

This is my script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class animation : MonoBehaviour
{
    Animator Ani;
    public Transform attackPoint;
    public float attackRange = 0.5f;
    public LayerMask enemyLayers;

    void Start()
    {
        Ani = GetComponent<Animator>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        { 
            Ani.SetTrigger("attack");

            Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
        }

        foreach(Collider2D enemy in hitEnemies)
        {
            Debug.Log("hit"   enemy.name);
        }
    }
}

how can i fix it?

CodePudding user response:

Since you do

if (Input.GetKeyDown(KeyCode.Space))
{ 
    Ani.SetTrigger("attack");

    Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
}
    

the variable hitEnemies does only exist in the scope within that if block

=> You want to either move the other code in there as well:

if (Input.GetKeyDown(KeyCode.Space))
{ 
    Ani.SetTrigger("attack");

    Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);


    foreach(Collider2D enemy in hitEnemies)
    {
        Debug.Log("hit"   enemy.name);
    }
}

or have a variable that always exists ... and then check again (I would prefer the first way)

Collider2D[] hitEnemies = null;

if (Input.GetKeyDown(KeyCode.Space))
{ 
    Ani.SetTrigger("attack");

    hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
}

if(hitEnemies != null)
{
    foreach(Collider2D enemy in hitEnemies)
   {
       Debug.Log("hit"   enemy.name);
   }
}
  • Related