Problem with arrays and accessing sriptable objects.

public Weapon weapons;
public int currentWeapon;

    shootRay.origin = weapons[currentWeapon].bulletSpawnPoint.transform.position;
    shootRay.direction = weapons[currentWeapon].bulletSpawnPoint.transform.forward;

    if (Physics.Raycast(shootRay, out raycastHit, weapons[currentWeapon].range))


I want to access variables in Weapon script (scriptableobject) from Shooting(up) script but i have error:
IndexOutRangeException: Array index is out of range.

Please help and thx.

  1. Always check for array lengths. Unless it’s static arrays.
  2. You should use polymorphism to shoot a weapon. Rather than having a single external class managing how each weapon shoots, implement a method called Shoot or something explicit like that and call it for the current weapon. That way your external class won’t have to worry about how shooting is done, it will simply know it can shoot.

Form what i can see there is 3 things that come to mind.

  1. Your array is not filled the way you think it is, so when you say currentWeapon= 6 the array might only have 4(OR 0) actual weapons in the array . Double check the inspector and count how meny you have / see.
  2. Some other scripts is messing with your values, are you 100% that currentWeapon and weapons or only being used in this scripts. They are public so there is a chance maybe you or someone els did something somewhere.
  3. Remember arrays/indexes start at 0 so if currentWeapon = 0 that is the first(1) weapon, so if currentWeapon = 1 that is your second(2) weapon. Computers AM i rite? LEL

Might not help right now but this is a very helpful tool when debugging just print some values out see what is happening with your currentWeapon and Weapon.