- Home /
Too subjective and argumentative
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.
Hi @berkgokhann - Have you actually assigned anything to your array in inspector / from code or are you accessing your array past it's last element perhaps?
You should check the weapons length and currentWeapon. $$anonymous$$ake sure you actually assigned some scriptableobject in the inspector.
Answer by madks13 · Aug 17, 2018 at 08:40 PM
Always check for array lengths. Unless it's static arrays.
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.
Answer by RustyCrow · Aug 17, 2018 at 10:15 PM
Form what i can see there is 3 things that come to mind.
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.
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.
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.
Follow this Question
Related Questions
IndexOutOfRangeException: Array index is out of range. 2 Answers
Set types of scripts i can place in ScriptableObject[] 1 Answer
Problem with Singleton and NullReferenceException? 0 Answers
How to learn amount of objects in selected prefabs folder? 0 Answers
IndexOutOfRangeException error for array points in range 1 Answer