Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Galve · Sep 12, 2015 at 07:12 PM · c#indexoutofrangeexceptionarray-out-of-range-except

IndexOutOfRangeException: Array index is out of range. WeaponManager.Start () (at Assets/Resources/NewScripts/WeaponManager.cs:55)

using UnityEngine; using System.Collections;

public class WeaponManager : MonoBehaviour {

 public GameObject[] weaponsInUse;                    
 public GameObject[] weaponsInGame;                    
 public Rigidbody[] worldModels;                         
 
 public RaycastHit hit;
 public float distance = 2.0f;
 public LayerMask layerMaskWeapon;
 public LayerMask layerMaskAmmo;
 public LayerMask layerMaskPurchase;
 
 public Transform dropPosition;
 
 public float switchWeaponTime = 0.5f;
 [HideInInspector]
 public bool canSwitch = true;
 [HideInInspector]
 public bool showWepGui = false;
 [HideInInspector]
 public bool showAmmoGui = false;
 public bool showPurchaseGui = false;
 
 
 private bool equipped = false;
 //[HideInInspector]
 //int i = 0;
 //[HideInInspector]
 public int weaponToSelect;
 //[HideInInspector]
 public int setElement;
 public int setPrice;
 public int setPriceAmmo;
 
 
 //[HideInInspector]
 public int weaponToDrop;
 public GUISkin mySkin;
 public AudioClip pickupSound;
 private string textFromPickupScript = "";
 private string notes = "";
 private string note = "Press key <E> to pick up Ammo";
 private string note2 = "Select appropriate weapon to pick up ammo";
 
 void Start()
 {
     for (int h = 0; h < worldModels.Length; h++)
     {
         weaponsInGame[h].gameObject.SetActive(false);
     }
     weaponToSelect = 0;
     DeselectWeapon();
 }
 void Update()
 {
     
     if (Input.GetKeyDown("1") && weaponsInUse.Length >= 1 && canSwitch && weaponToSelect != 0)
     {
         DeselectWeapon();
         weaponToSelect = 0;
         
     }
     else if (Input.GetKeyDown("2") && weaponsInUse.Length >= 2 && canSwitch && weaponToSelect != 1)
     {
         DeselectWeapon();
         weaponToSelect = 1;
         
     }
     
     if (Input.GetAxis("Mouse ScrollWheel") > 0 && canSwitch)
     {
         weaponToSelect++;
         if (weaponToSelect > (weaponsInUse.Length - 1))
         {
             weaponToSelect = 0;
         }
         DeselectWeapon();
     }
     
     if (Input.GetAxis("Mouse ScrollWheel") < 0 && canSwitch)
     {
         weaponToSelect--;
         if (weaponToSelect < 0)
         {
             weaponToSelect = weaponsInUse.Length - 1;
         }
         DeselectWeapon();
     }
     
     Vector3 position = transform.parent.position;
     Vector3 direction = transform.TransformDirection(Vector3.forward);
     if (Physics.Raycast(position, direction, out hit, distance, layerMaskWeapon.value))
     {
         
         WeaponIndex prefab = hit.transform.GetComponent<WeaponIndex>();
         setElement = prefab.setWeapon;
         showWepGui = true;
         //if you want more than 2 weapons equip at the same time        
         if (weaponsInUse[0] != weaponsInGame[setElement] && weaponsInUse[1] != weaponsInGame[setElement])
         { //&& weaponsInUse[2] != weaponsInGame[setElement] && weaponsInUse[3] != weaponsInGame[setElement]){
             equipped = false;
         }
         else
         {
             equipped = true;
         }
         
         if (canSwitch)
         {
             if (!equipped && Input.GetKeyDown("e"))
             {
                 DropWeapon(weaponToDrop);
                 DeselectWeapon();
                 weaponsInUse[weaponToSelect] = weaponsInGame[setElement];
                 if (setElement == 8)
                 {
                     Pickup pickupGOW1 = hit.transform.GetComponent<Pickup>();
                     addStickGrenades(pickupGOW1.amount);
                 }
                 Destroy(hit.collider.transform.parent.gameObject);
                 
             }
             else
             {
                 
                 if (Input.GetKeyDown("e"))
                 {
                     if (setElement == 8)
                     {
                         Pickup pickupGOW = hit.transform.GetComponent<Pickup>();
                         addStickGrenades(pickupGOW.amount);
                         Destroy(hit.collider.transform.parent.gameObject);
                     }
                 }
                 
             }
         }
         
     }
     else
     {
         showWepGui = false;
     }
     
     
     
     
     
     
     if (Physics.Raycast(position, direction, out hit, distance, layerMaskPurchase.value))
     {
         
         WeaponIndex prefab = hit.transform.GetComponent<WeaponIndex>();
         setElement = prefab.setWeapon;
         setPrice = prefab.setPrice;
         setPriceAmmo = setPrice/5;
         showPurchaseGui = true;
         //if you want more than 2 weapons equip at the same time        
         if (weaponsInUse[0] != weaponsInGame[setElement] && weaponsInUse[1] != weaponsInGame[setElement])
         { //&& weaponsInUse[2] != weaponsInGame[setElement] && weaponsInUse[3] != weaponsInGame[setElement]){
             equipped = false;
         }
         else
         {
             equipped = true;
         }
         
         if (canSwitch)
         {
             if (!equipped && Input.GetKeyDown("e") && GameManagement.playerCash >= setPrice)
             {
                 //DropWeapon(weaponToDrop);
                 DeselectWeapon();
                 GameManagement.playerCash -= setPrice;
                 weaponsInUse[weaponToSelect] = weaponsInGame[setElement];
                 if (setElement == 8)
                 {
                     Pickup pickupGOW1 = hit.transform.GetComponent<Pickup>();
                     addStickGrenades(pickupGOW1.amount);
                 }
                 Destroy(hit.collider.transform.parent.gameObject);
                 
             }
             else
             {
                 
                 if (Input.GetKeyDown("e") && GameManagement.playerCash >= setPriceAmmo)
                 {
                     if (setElement == 8)
                     {
                         Pickup pickupGOW = hit.transform.GetComponent<Pickup>();
                         addStickGrenades(pickupGOW.amount);
                         Destroy(hit.collider.transform.parent.gameObject);
                     }
                     else
                     {
                         BuyAmmo (setElement);
                         GameManagement.playerCash -= setPriceAmmo;
                     }
                 }
                 
             }
         }
         
     }
     else
     {
         showPurchaseGui = false;
     }
     
     
     
     
     
     
     
     
     if (Physics.Raycast(position, direction, out hit, distance, layerMaskAmmo.value))
     {
         showAmmoGui = true;
         
         if (hit.transform.CompareTag("Ammo"))
         {
             Pickup pickupGO = hit.transform.GetComponent<Pickup>();
             
             //ammo for pistols, rifles 
             if (pickupGO.pickupType == PickupType.Magazines)
             {
                 WeaponScriptNEW mags = weaponsInUse[weaponToSelect].gameObject.transform.GetComponent<WeaponScriptNEW>();
                 if (mags != null && mags.firstMode != fireMode.launcher)
                 {
                     notes = "";
                     textFromPickupScript = note;
                     if (Input.GetKeyDown("e"))
                     {
                         if (mags.ammoMode == Ammo.Magazines)
                         {
                             mags.magazines += pickupGO.amount;
                         }
                         else
                         {
                             mags.magazines += pickupGO.amount * mags.bulletsPerMag;
                         }
                         audio.clip = pickupSound;
                         audio.Play();
                         Destroy(hit.collider.gameObject);
                     }
                 }
                 else
                 {
                     textFromPickupScript = pickupGO.AmmoInfo;
                     notes = note2;
                 }
             }
             //ammo for Sniper rifle
             if (pickupGO.pickupType == PickupType.SniperMagazines)
             {
                 SniperScript magsSniper = weaponsInUse[weaponToSelect].gameObject.transform.GetComponent<SniperScript>();
                 if (magsSniper != null)
                 {
                     notes = "";
                     textFromPickupScript = note;
                     if (Input.GetKeyDown("e"))
                     {
                         magsSniper.magazines += pickupGO.amount;
                         audio.clip = pickupSound;
                         audio.Play();
                         Destroy(hit.collider.gameObject);
                     }
                 }
                 else
                 {
                     textFromPickupScript = pickupGO.AmmoInfo;
                     notes = note2;
                 }
             }
             //ammo for weapon if second fireMode is luancher
             if (pickupGO.pickupType == PickupType.Projectiles)
             {
                 WeaponScriptNEW projectile = weaponsInUse[weaponToSelect].gameObject.transform.GetComponent<WeaponScriptNEW>();
                 if (projectile != null && projectile.secondMode == fireMode.launcher)
                 {
                     notes = "";
                     textFromPickupScript = note;
                     if (Input.GetKeyDown("e"))
                     {
                         projectile.projectiles += pickupGO.amount;
                         audio.clip = pickupSound;
                         audio.Play();
                         Destroy(hit.collider.gameObject);
                     }
                 }
                 else
                 {
                     textFromPickupScript = pickupGO.AmmoInfo;
                     notes = note2;
                 }
             }
             //ammo for rocket launcher
             if (pickupGO.pickupType == PickupType.Rockets)
             {
                 WeaponScriptNEW rockets = weaponsInUse[weaponToSelect].gameObject.transform.GetComponent<WeaponScriptNEW>();
                 if (rockets != null && rockets.firstMode == fireMode.launcher)
                 {
                     notes = "";
                     textFromPickupScript = note;
                     if (Input.GetKeyDown("e"))
                     {
                         rockets.projectiles += pickupGO.amount;
                         //rockets.EnableProjectileRenderer();
                         audio.clip = pickupSound;
                         audio.Play();
                         Destroy(hit.collider.gameObject);
                     }
                 }
                 else
                 {
                     textFromPickupScript = pickupGO.AmmoInfo;
                     notes = note2;
                 }
             }
             //ammo for shotgun
             if (pickupGO.pickupType == PickupType.Shells)
             {
                 ShotGunScriptNEW bullets = weaponsInUse[weaponToSelect].gameObject.transform.GetComponent<ShotGunScriptNEW>();
                 if (bullets != null)
                 {
                     notes = "";
                     textFromPickupScript = note;
                     
                     if (Input.GetKeyDown("e"))
                     {
                         bullets.magazines += pickupGO.amount;
                         audio.clip = pickupSound;
                         audio.Play();
                         Destroy(hit.collider.gameObject);
                     }
                 }
                 else
                 {
                     textFromPickupScript = pickupGO.AmmoInfo;
                     notes = note2;
                 }
             }
             //pickup health
             if (pickupGO.pickupType == PickupType.Health)
             {
                 textFromPickupScript = pickupGO.AmmoInfo;
                 notes = "";
                 if (Input.GetKeyDown("e"))
                 {
                     GameObject playerGO = GameObject.Find("Player");
                     PlayerDamageNew hp = playerGO.gameObject.transform.GetComponent<PlayerDamageNew>();
                     hp.hitPoints += pickupGO.amount;
                     audio.clip = pickupSound;
                     audio.Play();
                     Destroy(hit.collider.gameObject);
                 }
             }
         }
         
     }
     else
     {
         showAmmoGui = false;
     }
 }
 
 
 
 void BuyAmmo(int weaponIndex)
 {
     if(weaponIndex == 0) //Scar
     {
         WeaponScriptNEW mags = weaponsInUse[weaponToSelect].gameObject.transform.GetComponent<WeaponScriptNEW>();
         mags.magazines += 100;
     }
     else if(weaponIndex == 5)
     {
         ShotGunScriptNEW bullets = weaponsInUse[weaponToSelect].gameObject.transform.GetComponent<ShotGunScriptNEW>();
         bullets.magazines += 14;
     }
 }
 
 void addStickGrenades(int amount)
 {
     GrenadeScript stickGrenade = weaponsInGame[8].gameObject.transform.GetComponent<GrenadeScript>();
     stickGrenade.grenadeCount += amount;
     stickGrenade.DrawWeapon();
 }
 
 void OnGUI()
 {
     GUI.skin = mySkin;
     GUIStyle style1 = mySkin.customStyles[0];
     if (showWepGui)
     {
         if (!equipped)
         {
             GUI.Label(new Rect(Screen.width - (Screen.width / 1.7f), Screen.height - (Screen.height / 1.4f), 800, 100), "Press key << E >> to pickup weapon", style1);
         }
         else
         {
             GUI.Label(new Rect(Screen.width - (Screen.width / 1.7f), Screen.height - (Screen.height / 1.4f), 800, 100), "Weapon is already equipped, Press <<E>> to Reload");
         }
     }
     
     if (showPurchaseGui)
     {
         if (!equipped)
         {
             GUI.Label(new Rect(Screen.width - (Screen.width / 1.7f), Screen.height - (Screen.height / 1.4f), 800, 100), "Press key << E >> to purchase weapon  $" + setPrice, style1);
         }
         else
         {
             GUI.Label(new Rect(Screen.width - (Screen.width / 1.7f), Screen.height - (Screen.height / 1.4f), 800, 100), "Press <<E>> to buy ammo  $" + setPriceAmmo);
         }
     }
     
     if (showAmmoGui)
     {
         GUI.Label(new Rect(Screen.width - (Screen.width / 1.7f), Screen.height - (Screen.height / 1.4f), 800, 200), notes + "\n" + textFromPickupScript, style1);
     }
 }
 
 void DeselectWeapon()
 {
     //Dectivate all weapon
     for (int i = 0; i < weaponsInUse.Length; i++)
     {
         weaponsInUse[i].gameObject.SendMessage("Deselect", SendMessageOptions.DontRequireReceiver);
         /*Component[] deactivate = weaponsInUse[i].gameObject.GetComponentsInChildren<MonoBehaviour>();
         foreach (var d in deactivate)
         {
             MonoBehaviour d = d as MonoBehaviour;
             if (d)
                 d.enabled = false;
         }*/
         weaponsInUse[i].gameObject.SetActive(false);
     }
     StartCoroutine(Wait());
 }
 
 IEnumerator Wait()
 {
     canSwitch = false;
     yield return new WaitForSeconds(switchWeaponTime);
     SelectWeapon(weaponToSelect);
     yield return new WaitForSeconds(switchWeaponTime);
     canSwitch = true;
 }
 
 void SelectWeapon(int i)
 {
     //Activate selected weapon
     weaponsInUse[i].gameObject.SetActive(true);
     /*Component[] activate = weaponsInUse[i].gameObject.GetComponentsInChildren<MonoBehaviour>();
     foreach (var a in activate)
     {
         MonoBehaviour a = a as MonoBehaviour;
         if (a)
             a.enabled = true;
     }*/
     weaponsInUse[i].gameObject.SendMessage("DrawWeapon", SendMessageOptions.DontRequireReceiver);
     WeaponIndex temp = weaponsInUse[i].gameObject.transform.GetComponent<WeaponIndex>();
     weaponToDrop = temp.setWeapon;
 }
 
 void DropWeapon(int index)
 {
     
     for (int i = 0; i < worldModels.Length; i++)
     {
         if (i == index)
         {
             Rigidbody drop = Instantiate(worldModels[i], dropPosition.transform.position, dropPosition.transform.rotation) as Rigidbody;
             drop.AddRelativeForce(0, 50, Random.Range(100, 200));
         }
     }
 }
 
 

}

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Galve · Sep 12, 2015 at 12:05 PM 0
Share

Line 55 is in the line 47

avatar image Graham-Dunnett ♦♦ · Sep 12, 2015 at 07:12 PM 0
Share

No need to upload nearly 500 lines of your code, surely? So, your Update() is accessing weaponsInGame. How big is that? $$anonymous$$aybe it's not got any objects in it.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by hexagonius · Sep 12, 2015 at 09:38 PM

you're using the index variable h for a different array from the one you're using the Length of in the loop. use the same arrays.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

C# array index is out of range, but is never set to be out of range [Fixed] 1 Answer

C# List index confusion using Mathf.Clamp 1 Answer

First Person Controller error, "IndexOutOfRangeException:Array index is out of range." 1 Answer

[C#] Error in script [IndexOutOfRangeException] 1 Answer

array index out of range 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges