Hi all, I’ve been staring at this piece of code for the last 2 hours now trying to debug it, and I cant see the woods for the trees anymore. I’m going out of my mind so please can someone help me!!
Basically, I have two methods to switch weapons:
IEnumerator NextWeapon()
{
if(!changingWeapon)
{
changingWeapon = true;
int weaponToChangeTo = _playerGunManager.currentWeapon += 1;
if (weaponToChangeTo == _playerGunManager.weapons.Length)
{
weaponToChangeTo = 0;
}
if (_playerGunManager.weapons[weaponToChangeTo].owned == false)
{
while (_playerGunManager.weapons[weaponToChangeTo].owned == false)
{
weaponToChangeTo += 1;
if (weaponToChangeTo == _playerGunManager.weapons.Length)
{
weaponToChangeTo = 0;
}
yield return null;
}
}
_playerGunManager.ChangeWeapon(weaponToChangeTo);
yield return new WaitForSeconds(0.2f);
changingWeapon = false;
}
yield return null;
}
IEnumerator PreviousWeapon()
{
if(!changingWeapon)
{
changingWeapon = true;
int weaponToChangeTo = _playerGunManager.currentWeapon -= 1;
if (weaponToChangeTo < 0)
{
weaponToChangeTo = _playerGunManager.weapons.Length - 1;
}
if (_playerGunManager.weapons[weaponToChangeTo].owned == false)
{
while (_playerGunManager.weapons[weaponToChangeTo].owned == false)
{
weaponToChangeTo -= 1;
if (weaponToChangeTo < 0)
{
weaponToChangeTo = _playerGunManager.weapons.Length - 1;
}
yield return null;
}
}
_playerGunManager.ChangeWeapon(weaponToChangeTo);
yield return new WaitForSeconds(0.2f);
changingWeapon = false;
}
yield return null;
}
The methods are called using the following:
if(!_playerGunManager.currentlyReloading)
{
if(_player.GetButtonDown("Next_Weapon"))
{
StartCoroutine(NextWeapon());
}
if (_player.GetButtonDown("Previous_Weapon"))
{
StartCoroutine(PreviousWeapon());
}
}
So… easy peasy so far.
But, the problem I have is that my methods are basically trying to iterate through an array of weapons, find ones that the player owns and then switch to that weapon, using an integer array value.
The thing is, when I call either function, the variable below is changed immediately
_playerGunManager.currentWeapon
Now at the end of the methods, they are calling another method that sets the current weapon on the playergunmanager:
public void ChangeWeapon(int weap)
{
aSource.playerAudio.PlayOneShot(weaponSwapSound, 0.2f);
currentWeapon = weap;
SetWeaponOptions();
_uiBulletManager.RefreshBullets();
_weaponIconManager.SetIcons();
}
Now this is the problem I cant figure out, why the hell is that variable changing immediately when its not changed until the end of the function.
At the game start, the players weapon variable is set at 0. As soon as you press the button for next or previous weapon, it goes to either -1 or 1, until and then changes to the correct value after iterating through the array in the IEnumerator, but nothing is changing it
I am problably being beyond stupid here, but its late and I cant go to bed until this works !
Please help! ![]()