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 /
avatar image
0
Question by ItachiUJorge · Jan 24, 2016 at 10:01 PM · instantiaterandomobjectsrandom.range

I made this script to instantiate objects, but when the game starts I get this error:IndexOutOfRangeException: Array index is out of range.

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class TileManager : MonoBehaviour {

 public GameObject[] tilePrefabs;

 public GameObject currentTile;

 private static TileManager instance;

 private Stack<GameObject> leftTiles = new Stack<GameObject>();

 private Stack<GameObject> topTiles = new Stack<GameObject>();

 private Stack<GameObject> rightTiles = new Stack<GameObject>();

 public static TileManager Instance 
 {
     get 
     {
         if (instance == null) 
         {
             instance = GameObject.FindObjectOfType<TileManager> ();
         }

         return instance;

     }
 }

 public Stack<GameObject> LeftTiles
 {
     get
     {
         return leftTiles;
     }

     set
     {
         leftTiles = value;
     }
 }

 public Stack<GameObject> TopTiles
 {
     get
     {
         return topTiles;
     }

     set
     {
         topTiles = value;
     }
 }

 public Stack<GameObject> RightTiles
 {
     get
     {
         return rightTiles;
     }

     set
     {
         rightTiles = value;
     }
 }

 // Use this for initialization
 void Start () 
 {
     
     CreateTiles (30);
     
     for (int i = 0; i < 15; i++)
     {
         SpawnTiles ();
     }

 }
                                                                                                                                                                                         
 // Update is called once per frame
 void Update () {
 
 }
     
 public void CreateTiles (int amount)
 {
     for (int i = 0; i < amount; i++)
     {
         LeftTiles.Push (Instantiate (tilePrefabs [0]));
         TopTiles.Push (Instantiate (tilePrefabs [1]));
         RightTiles.Push (Instantiate (tilePrefabs[2]));
         TopTiles.Peek ().name = "TopTile";
         TopTiles.Peek ().SetActive (false);
         LeftTiles.Peek ().name = "LeftTile";
         LeftTiles.Peek ().SetActive (false);
         RightTiles.Peek ().name = "RightTile";
         RightTiles.Peek ().SetActive (false);
     }

 }

 public void SpawnTiles()
 {
     
     if (LeftTiles.Count == 0 || TopTiles.Count == 0 || RightTiles.Count == 0)
     {
         CreateTiles (15);
     }

     //Generating a random number between 0 and 1
     int randomIndex = Random.Range (0, 3);

     if (randomIndex == 0)
     {
         GameObject tmp = LeftTiles.Pop ();
         tmp.SetActive (true);
         tmp.transform.position = currentTile.transform.GetChild (0).transform.GetChild (randomIndex).position;
         currentTile = tmp;
     } 
     else if(randomIndex == 1)
     {
         GameObject tmp = TopTiles.Pop ();
         tmp.SetActive (true);
         tmp.transform.position = currentTile.transform.GetChild (0).transform.GetChild (randomIndex).position;
         currentTile = tmp;
     }
     else if (randomIndex == 2)
     {
         GameObject tmp = RightTiles.Pop();
         tmp.SetActive(true);
         tmp.transform.position = currentTile.transform.GetChild(0).transform.GetChild(randomIndex).position;
         currentTile = tmp;
     }

     currentTile = (GameObject)Instantiate (tilePrefabs[randomIndex], currentTile.transform.GetChild (0).transform.GetChild (randomIndex).transform.GetChild(randomIndex).position, Quaternion.identity);
 }

}

Comment
Add comment · Show 1
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 Bonfire-Boy · Jan 25, 2016 at 03:41 PM 1
Share

Doesn't the error tell you what line it's happening on?

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Graphics_Dev · Jan 24, 2016 at 11:06 PM

Line 110 should be:

 int randomIndex = Random.Range (0, tilePrefabs.Length);

You only check for 0, 1, and 2 so at line 133 you use tilePrefabs[randomIndex] which probably only has a length of 3.

Let me know if this helps ;)

Thanks for the corrective comments I voted you each up :)

Comment
Add comment · Show 5 · 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 ShadyProductions · Jan 24, 2016 at 11:10 PM 2
Share

Safer to do this, you'll never be wrong this way. =)

 Random.Range (0, tilePrefabs.Length);
avatar image Orami · Jan 25, 2016 at 04:35 AM 2
Share

If using floats: "Returns a random float number between and $$anonymous$$ [inclusive] and max [inclusive] (Read Only)."

If using ints: "Returns a random integer number between $$anonymous$$ [inclusive] and max [exclusive] (Read Only)."

source: http://docs.unity3d.com/ScriptReference/Random.Range.html

So you do not need to -1 from the length.

avatar image Graphics_Dev Orami · Jan 25, 2016 at 03:14 PM 0
Share

Sorry, didn't know max was exclusive for ints ;)

avatar image Orami Graphics_Dev · Jan 25, 2016 at 03:58 PM 0
Share

It's one of those things that lingers with us all from C++, just wanted to clarify for the OP.

avatar image Graphics_Dev · Jan 25, 2016 at 04:19 PM 1
Share

If there are no tilePrefabs size is 0,

"If max equals $$anonymous$$, $$anonymous$$ will be returned. The returned value will never be max unless $$anonymous$$ equals max."

$$anonymous$$in will be 0 and max will be 0, therefore $$anonymous$$ = max, therefore the returned value will be 0 which will raise an error because 0 will be out of range.

If a randomly selected slot does not have an assigned prefab,

you will raise a null exception (the object you are trying to access is null)...

to check for these two potential errors put this in your start function:

 // check if length is 0 to avoid out of range exception
 if (tilePrefabs.Length == 0) {
     Debug.LogError ("No tilePrefabs are assigned!");
 }
 // check if all slots are filled
 for (int i = 0; i < tilePrefabs.Length; i++){
     if (tilePrefabs[i] == null) {
         Debug.LogError ("$$anonymous$$issing tilePrefab!");
     }
 }

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

6 People are following this question.

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

Related Questions

Random.range multiple instantiations without repetition 1 Answer

Instantiate Random Object at Random Position 1 Answer

How can I Instantiate an Object from a Randomly Selected Index in an Array of Game Objects? 1 Answer

How to get randomly spawning objects across a map 2 Answers

Randomizing a selection from an array 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