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 bf01 · Feb 14, 2016 at 11:11 PM · c#array of gameobjects

Array index out of range c#

Code in question:

 public static int Points = 0;
 private int counter = 1;

void start() { public GameObject[] Obstacles; }

void Update() { if (Points % 5 == 0 && Points - counter * 5 == 0) { Debug.Log("Points: " + Points + "counter: " + counter); Obstacles[counter].SetActive(true); counter++; } }

This is the main part. When i run the program and the if loop triggers, I am told that the Array index is out of reach. I've snipped out a lot of the code that is unnecessary and has nothing to do with this part.

Comment
Add comment · Show 3
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 Ahndrakhul · Feb 14, 2016 at 11:36 PM 1
Share

You might not have included enough code here to see what's going on.

The s in start needs to be capitalized to use the unity Start() function, but then you will get an error because this:

 void Start()
 { 
     public GameObject[] Obstacles; 
 }

isn't valid. you probably want to move that declaration up to where you are declaring your "Points" and "counter" variables. After that, how are you populating your Obstacles array? In the inspector? In some other code?

if you try to access your Obstacles array like this:

 Obstacles[counter].SetActive(true);

without populating it, you will get an index out of range error.

avatar image EmHuynh Ahndrakhul · Feb 15, 2016 at 03:09 AM 0
Share

Good response, @Ahndrakhul! +1 (:

avatar image bf01 Ahndrakhul · Feb 15, 2016 at 05:12 PM 0
Share

Yes, sorry. I did not include enough code and well the actual thing has all of the things you just mentioned.

Here's the real thing. This one also has a lot of the parts stripped, but it should do.

public class PlayerControls : $$anonymous$$onoBehaviour {

 public static int Points = 0;
 private int counter = 1;
 private GameObject[] Obstacles;
 void Start()
 {
   Obstacles = GameObject.FindGameObjectsWithTag("Obstacle");
 }
 void OnTriggerEnter(Collider other) 
 {
     if (other.gameObject.CompareTag ("Coin")) {
         Points += 1;
         timer += 2;
         if (Points % 5 == 0 && Points - counter * 5 == 0)
         {
             Debug.Log("Points: " + Points + "counter: " + counter);
             Obstacles[counter].SetActive(true);
             counter++;
       }
         UpdateScore ();
     }
     else if (other.gameObject.CompareTag ( "Obstacle"))
     {
         GameOver = true;
         GG.text = "GA$$anonymous$$E OVER";
     }
 }

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Salmjak · Feb 15, 2016 at 06:01 PM

Array index is out of range is an error due to trying to access an index that doesnt exist. Thus "out of range" where range is the size of the array or list.

In programming the first element is always referred to as "0", so obstacles[0] retrieves the first item. When you say "counter = 1" you actually say "start at the second item in the list/array". If the array/list don't have 2 items you will get the error.

What you could do to avoid this is using an if()-statement with the condition Obstacles.Length >= 2 (if you actually want to retrieve the second item and not the first) or even better, check that if(counter

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 lvaiciunas25 · Jul 12, 2018 at 12:02 PM

Could someone help me with this code? using System.Collections; using System.Collections.Generic; using UnityEngine;

[System.Serializable] public class Wave { public int EnemiesPerWave; public GameObject Enemy; } public class SpawnManager : MonoBehaviour { public Wave[] Waves; public Transform[] SpawnPoints; public float TimeBetweenEnemies = 2f;

 private int _totalEnemiesInCurrentWave;
 private int _enemiesInWaveLeft;
 private int _spawnedEnemies;

 private int _currentWave;
 private int _totalWaves;
 void Start () {
     _currentWave = -1;
     _totalWaves = Waves.Length - 1;
     StartNextWave();
 }
 
 // Update is called once per frame
 void StartNextWave() {
     if(_currentWave > _totalWaves)
     {
         return;
     }
     _totalEnemiesInCurrentWave = Waves[_currentWave].EnemiesPerWave;
     _enemiesInWaveLeft = 0;
     _spawnedEnemies = 0;

     StartCoroutine(SpawnEnemies());
 }
 IEnumerator SpawnEnemies()
 {
     GameObject enemy = Waves[_currentWave].Enemy;
     while (_spawnedEnemies < _totalEnemiesInCurrentWave)
     {
         _spawnedEnemies++;
         _enemiesInWaveLeft++;

         int spawnPointIndex = Random.Range(0, SpawnPoints.Length);
         Instantiate(enemy, SpawnPoints[spawnPointIndex].position, SpawnPoints[spawnPointIndex].rotation);
         yield return new WaitForSeconds(TimeBetweenEnemies);
     }
     yield return null;
 }
 public void EnemyDefeated()
 {
     _enemiesInWaveLeft--;
     if(_enemiesInWaveLeft == 0 && _spawnedEnemies == _totalEnemiesInCurrentWave)
     {
         StartNextWave();
     }
 }

} I get the Array index is out of range error when i launch the scene on 2 lines: StartNextWave(); _totalEnemiesInCurrentWave = Waves[_currentWave].EnemiesPerWave;,Could someone help me with this code? using System.Collections; using System.Collections.Generic; using UnityEngine;

[System.Serializable] public class Wave { public int EnemiesPerWave; public GameObject Enemy; } public class SpawnManager : MonoBehaviour { public Wave[] Waves; public Transform[] SpawnPoints; public float TimeBetweenEnemies = 2f;

 private int _totalEnemiesInCurrentWave;
 private int _enemiesInWaveLeft;
 private int _spawnedEnemies;

 private int _currentWave;
 private int _totalWaves;
 void Start () {
     _currentWave = -1;
     _totalWaves = Waves.Length - 1;
     StartNextWave();
 }
 
 // Update is called once per frame
 void StartNextWave() {
     if(_currentWave > _totalWaves)
     {
         return;
     }
     _totalEnemiesInCurrentWave = Waves[_currentWave].EnemiesPerWave;
     _enemiesInWaveLeft = 0;
     _spawnedEnemies = 0;

     StartCoroutine(SpawnEnemies());
 }
 IEnumerator SpawnEnemies()
 {
     GameObject enemy = Waves[_currentWave].Enemy;
     while (_spawnedEnemies < _totalEnemiesInCurrentWave)
     {
         _spawnedEnemies++;
         _enemiesInWaveLeft++;

         int spawnPointIndex = Random.Range(0, SpawnPoints.Length);
         Instantiate(enemy, SpawnPoints[spawnPointIndex].position, SpawnPoints[spawnPointIndex].rotation);
         yield return new WaitForSeconds(TimeBetweenEnemies);
     }
     yield return null;
 }
 public void EnemyDefeated()
 {
     _enemiesInWaveLeft--;
     if(_enemiesInWaveLeft == 0 && _spawnedEnemies == _totalEnemiesInCurrentWave)
     {
         StartNextWave();
     }
 }

} im getting the error when i launch the scene at StartNextWave(); and _totalEnemiesInCurrentWave = Waves[_currentWave].EnemiesPerWave;

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 Skelly1983 · Jul 13, 2018 at 05:40 PM 0
Share

This should be posted as a new question, or a comment to avoid duplication, not an answer.

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

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How can I check the color of GameObjects in an Array and print out their color? 0 Answers

how to save positions in Vector3 Array und move playerobjekt to the saved position in array's?? 1 Answer

Check state of variable for each item in an Array 1 Answer

how to create an array of gameobjects by using raycast? 1 Answer

Help with arrays and checking other object's floats 0 Answers


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