当前上下文中不存在名称“” - Unity 3D

The name '' does not exist in the current context - Unity 3D

我收到错误 The name 'AK74' does not exist in the current context and The name 'STG44' does not exist in the current context in both Debug.Log lines

有什么解决办法吗?

     private void Start()
    {
        weapon = GetComponent<Weapon>();

        Weapon AK74 = new Weapon(2, 30, 200);
        Weapon STG44 = new Weapon(1, 35, 200);

        _currentAmmoInClip = clipSize;
        STG44.Setmagsize(_currentAmmoInClip);

        _ammoInReserve = reservedAmmoCapacity;
        STG44.Setfullmag(_ammoInReserve);
        _canShoot = true;


    }

    private void Update()
    {
        Debug.Log(AK74.Getmagsize());
        Debug.Log(STG44.Getmagsize());
    }

这些变量定义在Start方法的范围内,一旦这个函数完成,它们就会被删除。你想将它们存储在对象本身中,所以你必须在函数之外声明它们,在 class 本身中,如下所示:

Weapon AK74, STG44;

private void Start()
{
    weapon = GetComponent<Weapon>();

    AK74 = new Weapon(2, 30, 200);
    STG44 = new Weapon(1, 35, 200);

    _currentAmmoInClip = clipSize;
    STG44.Setmagsize(_currentAmmoInClip);

    _ammoInReserve = reservedAmmoCapacity;
    STG44.Setfullmag(_ammoInReserve);
    _canShoot = true;
}

private void Update()
{
    Debug.Log(AK74.Getmagsize());
    Debug.Log(STG44.Getmagsize());
}

Read up on variable scope and the use of fields.

简单地说,您在 Start 中声明的 AK47 和 STG44 变量仅存在于 Start 中,您必须将它们移出到主 class 中,以便它们在其他方法中仍然可用。花时间学习一些有关 C# 编程基本原理的教程,从长远来看会为您节省很多时间 运行。

AK47 和 STG44 变量是 Start() 的局部变量,不在更新范围内。要使它们可见,请通过将它们的声明移出 Start() 来扩大它们的范围。例如:

Weapon AK74 = new Weapon(2, 30, 200);
Weapon STG44 = new Weapon(1, 35, 200);

private void Start() {
    weapon = GetComponent<Weapon>();

    _currentAmmoInClip = clipSize;
    STG44.Setmagsize(_currentAmmoInClip);

    _ammoInReserve = reservedAmmoCapacity;
    STG44.Setfullmag(_ammoInReserve);
    _canShoot = true;
}