unity3d 错误CS0103:当前上下文中不存在名称ウhitEnemies Ж,

tjvv9vkg  于 2022-11-30  发布在  其他
关注(0)|答案(2)|浏览(380)

我是新的编码。我只是尝试编码一个小游戏,似乎有一个错误,我不能修复。有人能帮助我吗
这是我的剧本

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);
        }
    }
}

我该怎么修呢?

cgvd09ve

cgvd09ve1#

既然你这么做了

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

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

变量hitEnemies只存在于if块内的作用域
=〉你想把其他代码也移到这里:

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);
    }
}

或者有一个始终存在的变量...然后再次检查(我更喜欢第一种方式)

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);
   }
}
smdnsysy

smdnsysy2#

名称'hitEnemies'在目前内容中不存在

当前上下文:

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

存在于何处?:

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

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

只需移动变量所在的位置。

相关问题