This A robbery
This A robbery

Reputation: 13

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

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

Upvotes: 0

Views: 6057

Answers (3)

Vastlee
Vastlee

Reputation: 26

The AK47 and STG44 variables are local to Start(), and are out of scope for Update. To make them visible, increase their scope by moving their declaration out of Start(). For instance:

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

Upvotes: 1

Sven Viking
Sven Viking

Reputation: 2720

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.

Upvotes: 0

Alexey S. Larionov
Alexey S. Larionov

Reputation: 7927

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

Upvotes: 0

Related Questions