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 Glaciuss · May 12, 2016 at 01:52 PM · objectreference

IndexOutOfRangeException: Array index is out of range.

Please help me. How to edit this error I use Unity version 5.1.1f

IndexOutOfRangeException: Array index is out of range. EnemySpawner.SpawnEnemy (UnityEngine.GameObject enemy) (at Assets/scripts/enemy/EnemySpawner.cs:81) EnemySpawner.SpawnNext () (at Assets/scripts/enemy/EnemySpawner.cs:69) EnemySpawner.Update () (at Assets/scripts/enemy/EnemySpawner.cs:52)

EnemySpawner Script:

 /*
  * By Floris de Haan @ June 2015
  * Free to use for all purposes.
  */
 
 using UnityEngine;
 using System.Collections.Generic;
 
 /// <summary>
 /// Multifunctional enemy spawner class.
 /// </summary>
 public class EnemySpawner : MonoBehaviour
 {
     #region Vars
 
     [SerializeField]
     private EnemySpawnInfo[] _enemySpawnInfo;
     [SerializeField]
     private Transform _enemyParent;
     [SerializeField]
     private Transform[] _enemySpawnPositions;
 
     private List<GameObject> _enemies;
 
     [SerializeField]
     private float _spawnInterval = 1f;
     private float _spawnIntervalDecreasement = 0.01f;
     private float _spawnIntervalMin = 0.2f;
     private float _spawnTimer = 0f;
 
     [SerializeField]
     private int _maxEnemies = 20;
 
     #endregion
 
     #region Methods
 
     private void Start()
     {
         _enemies = new List<GameObject>();
     }
 
     private void Update()
     {
         if (_spawnTimer < _spawnInterval)
         {
             _spawnTimer += Time.deltaTime;
 
             if (_enemies.Count < _maxEnemies && _spawnTimer > _spawnInterval)
             {
                 _spawnTimer -= _spawnInterval;
                 SpawnNext();
                 if (_spawnInterval > _spawnIntervalMin) _spawnInterval -= _spawnIntervalDecreasement;
             }
         }
     }
 
     private void SpawnNext()
     {
         // Random percentage
         int rnd = Random.Range(0, 99);
         
         foreach (EnemySpawnInfo item in _enemySpawnInfo)
         {
             // Check if random is in chance
             if (rnd < item.chance)
             {
                 print("Spawn item: " + item.Enemy.name);
                 SpawnEnemy(item.Enemy);
                 break;
             }
 
             // Fix chance for next item
             rnd -= (int)item.chance;
         }
     }
 
     private void SpawnEnemy(GameObject enemy)
     {
         // Random spawn pos
         Transform rndSpawn = _enemySpawnPositions[Random.Range(0, _enemySpawnPositions.Length)];
 
         // Spawn
         GameObject newEnemy = (GameObject)Instantiate(enemy, rndSpawn.position, rndSpawn.rotation);
         if (_enemyParent != null) newEnemy.transform.parent = _enemyParent;
         _enemies.Add(newEnemy);
 
         // Wait untill dead
         EnemyHandler enemyHandler = newEnemy.GetComponent<EnemyHandler>();
         enemyHandler.GetDamageEvent += () => {
             RemoveEnemy(newEnemy);
         };
     }
 
     private void RemoveEnemy(GameObject enemy)
     {
         _enemies.Remove(enemy);
 
         // Reset timer to spawn next if already stopped
         if (_spawnTimer >= _spawnInterval) _spawnTimer = 0f;
     }
 
     #endregion
 
     #region Properties
 
     #endregion
 }
 
 [System.Serializable]
 public struct EnemySpawnInfo
 {
     public GameObject Enemy; // Prefab
     public short chance; // (0 to 99) %
 }
Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Naphier · May 13, 2016 at 06:49 PM

Can you mark which line is throwing the error? When pasting code here it's really hard to tell if the line numbers match up with the console's stacktrace. First thing I see is that your List, _enemies, might be null, so when declaring it, just say

 private List<GameObject> _enemies = new List<GameObject>();

But the error you show has stack trace of line 81 which is pointing to _enemySpawnPositions being null. I assume you're assigning those in the inspector,

Next thing that sticks out is

 if (_enemyParent != null) newEnemy.transform.parent = _enemyParent;

The way to assign parents is this:

 newEnemy.transform.SetParent(_enemyParent.transform);

Do liberal checking of objects == null to make sure you aren't accessing null objects!

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
avatar image
0

Answer by Glaciuss · May 14, 2016 at 03:28 AM

Thank you for comment but it don't work it just show: IndexOutOfRangeException: Array index is out of range. in the same line 81, 69, 52 and I already googling to find solution but the error is still there.

Comment
Add comment · Show 1 · 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
avatar image Naphier · May 14, 2016 at 03:53 AM 0
Share

Then your index you're trying to put in to an array's brackets is out of range at those lines. I'd highly suggest you take a step back and work through some of the free introductory scripting tutorials.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

CameraController (object reference not set to an instance of an object) 1 Answer

Help for Quest System 2 Answers

I coundn't figure out this error .Please Anyone Can help me with this error 0 Answers

Can't access a method from another script (Object reference not set to an instance of an object) 1 Answer

How to Fix this issue 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