Home > Software engineering >  The name '' does not exist in the current context - Unity 3D
The name '' does not exist in the current context - Unity 3D

Time:04-03

i get the errors 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

any solution?

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

CodePudding user response:

Those variables are defined in the scope of Start method, and they will be deleted as soon as this function will finish. You want to store them in the object itself, so you have to declare them outside of function, in the class itself, like so:

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

CodePudding user response:

Read up on variable scope and the use of fields.

Put simply the AK47 and STG44 variables you declared within Start exist only within Start, and you have to move them out into the main class for them to remain available for use in other methods. Spending time going through some tutorials on basic C# programming principles will save you a lot of time in the long run though.

  • Related