Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 ardizzle · Nov 07, 2013 at 03:06 PM · javascriptarray

What am I doing wrong on my array?

i have a script that creates 10 gas stations. I need all 10 of those gas stations to be put into an array as they are created. I think I am close but I keep getting the error message index out of range.

 #pragma strict
 var gasStation : GameObject;
 var gasStationArray : GameObject[];
 var numberOfGasStationsToSpawn : int = 10;
 static var numberOfGasStations : int = 0;
 var test : int = 0;
 function Start () 
 {
 }
 
 function Update () 
 {
     CreateGasStations(); // This function will be deleted in the final project. 
 }
 
 function CreateGasStations()
 {
     // This is just for testing and setting up. Will be deleted later;
     if(numberOfGasStations < numberOfGasStationsToSpawn)
     {
         numberOfGasStations++;
         Instantiate (gasStation, Vector3(Random.Range(44.0,57.0), Random.Range(40.0,49.0), 0), Quaternion.identity);
         gasStationArray[numberOfGasStations] = GameObject.Find("Gas Station #" + numberOfGasStations);
     }
 }
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 vexe · Nov 07, 2013 at 09:33 PM 1
Share

Dear, why the use of static in numOfGasStations? Please stay away from statics unless you know what you're doing :) See this for an explanation. (skip to the good coding habits)

4 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer Wiki

Answer by rlarocca92 · Nov 07, 2013 at 06:24 PM

You have a few problems to address:

First you need to initialize the array. Initialization of this array should happen when the script starts. So add this line to your Start() function:

 gasStationArray = new GameObject[10];

This will make your variable, gasStationArray, a new array that can hold up to 10 GameObjects.

Your next problem is you call CreateGasStations() in the Update() function. This will cause this function to be run once per frame, but you only want to do this once when the script starts. To fix this, simply call CreateGasStations() in your Start() function instead of Update(). But make sure to call it after you initialize the array. You also have to remove it from your Update() function. So your Start() function should look like this:

 function Start()
 {
     gasStationArray = new GameObject[10];
     CreateGasStations();
 }

Your next problem is you use numberOfGasStations to select an index from your array. The issue you have here is that you increment numberOfGasStations before you select from the array. Array index start at 0. So for example, your array has 10 items, so the index of the array is 0 - 9. Any other number will give you an index out of bounds exception. To fix this move:

 numberOfGasStations++;

below

  gasStationArray[numberOfGasStations] = GameObject.Find("Gas Station #" + numberOfGasStations);

The last thing I will point out is how you find the object you just created. Instead of using GameObject.find() after you create the new gas station, the Instantiate function will return the game object that was created. You can save the new object to a variable, then put it into the array. So this is how CreateGasStations() should look:

 function CreateGasStations()
 {
     if(numberOfGasStations < numberOfGasStationsToSpawn)
     {
         var newStation : GameObject = Instantiate (gasStation, Vector3(Random.Range(44.0,57.0), Random.Range(40.0,49.0), 0), Quaternion.identity);
         gasStationArray[numberOfGasStations] = newStation;
         numberOfGasStations++;
     }
 }
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 ardizzle · Nov 08, 2013 at 11:44 PM 0
Share

Thanks so much man. I have it working perfectly. And thanks for going into so much depth. Really helped me understand it.

The only thing that I have to say though is that putting CreateGasStations(); in the start functions only creates one gas station. Which is why I had it in update. And I know how to make them all spawn at the start but im pretty sure that the final product will need to be kept in update due to the possibility that the number of stations could rise at any time.

avatar image
2

Answer by Immanuel-Scholz · Nov 07, 2013 at 03:12 PM

Array indicies are starting with 0, not 1. (So the first index is 0). You increment numberOfGasStations and THEN add it to the array, so your first index is 1.

Just move the numberOfGasStations++ below the gasStationArray[...] line.

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 ardizzle · Nov 07, 2013 at 04:12 PM 0
Share

I just tried that and I get the same error IndexOutOfRangeException: Array index is out of range.

avatar image
1

Answer by Eric5h5 · Nov 07, 2013 at 05:03 PM

You haven't initialized your gasStationArray to numberOfGasStationsToSpawn anywhere. It's being initialized in the inspector, so it's almost certainly wrong. Also, don't put the CreateGasStations function call in Update, not even for testing. Update runs once every frame.

Comment
Add comment · Show 2 · 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 ardizzle · Nov 07, 2013 at 05:30 PM 0
Share

Im still lost. Im pretty new to arrays. I could never get them to work right. Also what would you suggest to put it in ins$$anonymous$$d of update?

avatar image Eric5h5 · Nov 07, 2013 at 05:44 PM 0
Share

Start. "var foo = new int[10];" would initialize an int array to 10 items.

avatar image
1

Answer by clunk47 · Nov 07, 2013 at 09:28 PM

 #pragma strict
 
 private var stations : GameObject[] = new GameObject[10];
 var prefab : GameObject;
 
 function Start()
 {
     for(var i : int = 0; i < stations.Length; i++)
     {
         stations[i] = Instantiate(prefab, transform.position, Quaternion.identity);
     }
 }


Of course you will need your position to actually instantiate each, this just shows how to create 10 instances of a prefab on Start.

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

18 People are following this question.

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

Related Questions

Can someone help me fix my Javascript for Flickering Light? 6 Answers

Setting Scroll View Width GUILayout 1 Answer

How to find the opposite variables list? 1 Answer

Issue with some GUITextures and an Array [SOLVED] 1 Answer

Javascript - Calling a random String 2 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