0
\$\begingroup\$

I'm trying to make an RPG style game with equipment using ScriptableObject, but whenever I equip the item, it does not register in my JSON data.

Here is the script I use:

for (int i = 0; i < weaponItemSOs.Length; i++)
{
    if (weaponItemSOs[i].isEquiped == true)
    {
        selectedweapon = i;
    }
    else if (weaponItemSOs[i].isEquiped == false)
    {
        selectedweapon = -1;
    }
}
if(selectedweapon >= 0)
{
    power = 25 + weaponItemSOs[selectedweapon].attackBonus;
    distance = weaponItemSOs[selectedweapon].Shootdistance;
    ammo = weaponItemSOs[selectedweapon].ammo;
    currentammo = weaponItemSOs[selectedweapon].ammo;
}
else
{
    power = 25;
    distance = 20;
    ammo = 10;
    currentammo = 10;
}
PlayerGameManager.Power = power;
ShootEnemy.distanceOfRay = distance;
PlayerGameManager.Ammo = ammo;
PlayerGameManager.CurrentAmmo = currentammo;
JSONSaveSystem.SavePlayer();
\$\endgroup\$
1
  • \$\begingroup\$ Hint: imagine the player has equipped the weapon at index 0 in the weaponItemSOs[] array. What happens when your for loop reaches index i = 1? \$\endgroup\$
    – DMGregory
    May 31, 2021 at 19:47

1 Answer 1

1
\$\begingroup\$

Whenever your equipped weapon is not the last one in the array, the one immediately after it sets selectedweapon = -1 at the end. What you want to do is scan through the array until you find the equipped weapon, then stop searching.

Replace your for loop with something like this:

selectedweapon = -1;
for (int i = 0; i < weaponItemSOs.Length; i++)
{
    if (weaponItemSOs[i].isEquiped)
    {
        selectedweapon = i;
        break;
    }
}

Or as a one-liner:

selectedWeapon = System.Array.FindIndex(weaponItemSOs, weapon => weapon.isEquipped);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .