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 archiefied1 · Oct 31, 2014 at 03:51 PM · gameobjectarrayindexoutofrangeexceptionout of range

Array out of index?

So I have an enemy which is going to be patrolling around the area. I decided to make a gameobject array to find the objects with the tag "Waypoints" and then store the objects position in another array from a for loop and then assign those values to a target variable. I'm new to c# coding so I thought it made sense.

Anyway I logged the arrays and they weren't empty(it outputs their xyz values). I have the enemy set up (for testing) to move to the position when I press the letter M (It works when I use my position) using navmesh. When I change my target variable to "target = position[0]" and then test it, it outputs "Indexoutofrangeexception: array index is out of range"

So the above didn't work so I tried another method by using the waypoints array instead -> target = waypoints[0].transform.position

It gave me the same error.

I have the variable set up as public because if they aren't I get an error and then I apply the values in the start function because if I do it outside of it I get an error saying that the array waypoints doesn't exist or something.

So I tried every possible way (even applying the values manually -> waypoint[0] = gameobject.find("name") etc.) so any help is appreciated so here is the code, I don't understand if the array themselves aren't empty. Thanks.`using UnityEngine; using System.Collections;

[RequireComponent(typeof(NavMeshAgent))]

public class MannequinAI : MonoBehaviour {

 Animator anim;
 NavMeshAgent nav;
 Vector3 target;
 public GameObject[] waypoints; //array for the gameobjects
 public Vector3[] positions; //array to store their position

 // Use this for initialization
 void Start () {
             anim = GetComponent<Animator> ();
             nav = GetComponent<NavMeshAgent> ();
             anim.SetFloat ("Speed", 1);
             GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Waypoints");
             Vector3[] positions = new Vector3[waypoints.Length];

             if (positions.Length != 0) {
                     Debug.Log (waypoints[0].transform.position);
                     Debug.Log (waypoints[1].transform.position);
             }
     }
 
 // Update is called once per frame
 void Update () {
     if (Input.GetKeyDown (KeyCode.M)) {
                     navigation ();//goes to this function
             }

     if (!nav.pathPending)
     {
         if (nav.remainingDistance <= nav.stoppingDistance)
         {
             if (!nav.hasPath || nav.velocity.sqrMagnitude == 0f) //this code is just to check remaining distance from target to change animation.
             {
                 anim.SetFloat ("Speed", 0);
             }
         }
     }

     for (int i = 0; i < waypoints.Length; i++)
     {
         positions[i] = waypoints[i].transform.position; //store the positions with the index i
     }

             }
 void navigation() {
     target = positions[0]; //sets the target, this is the error line. I also tried it in update.
     nav.SetDestination(target); //this part works when target is set to my location.
     anim.SetFloat ("Speed", 1);
 }

} `

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 bubzy · Oct 31, 2014 at 03:56 PM 0
Share

add a debug line in navigation()

Debug.Log(positions[0]);

and maybe

'Debug.Log(positions.Length);`

do you get anything?

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Baste · Oct 31, 2014 at 04:13 PM

Okay, this answer comes in two parts: First the error, and then general advice!

The error:

You need to remember what scopes are. When you in Start write this:

 GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Waypoints");
 Vector3[] positions = new Vector3[waypoints.Length];

You're making two new, local arrays, named waypoints and positions. They've got nothing to do with the public waypoints and positions arrays. When Start finishes, the two new arrays you've made goes away, and the public (empty) ones stays unchanged.

Your fix is to refer to the public variables instead of declaring new arrays. Change the two lines above to this:

 waypoints = GameObject.FindGameObjectsWithTag("Waypoints");
 positions = new Vector3[waypoints.Length];

General advice:

You're doing something really strange here.

Having both waypoints and positions set as public arrays indicates that you want to assign them in the editor. That's fine and all, but you re-assign them in Start, so all the values you put in the editor will be overridden. You should either find them in Start, or assign them in the editor. Unless you have a really, really good reason, stick to what you're doing already and declare them as private instead of public:

 private GameObject[] waypoints; //array for the gameobjects
 private Vector3[] positions; //array to store their position

Secondarily, you're reassigning the values of the positions array in Update - on every frame of the game. That should really only need to happen once, in Start. So the for-loop you're assigning the positions in should go to Start.

Thirdly, you don't need both the positions array and the waypoints array. You could kill the entire positions array, and replace

 target = positions[0];

with

 target = waypoints[0].transform.position;
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 archiefied1 · Oct 31, 2014 at 04:29 PM 0
Share

Ah! Thank you I got it working! :) I knew something was wrong.

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

Simple Looping drag and drop game 1 Answer

HELP Find gameObject With tag in another array 1 Answer

Creating an array of prefabs? 4 Answers

Enabled all gameobjects in array 1 Answer

Checking if a position is occupied in 2D? 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