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 MachCUBED · Aug 14, 2012 at 06:02 AM · arraysnavigation

Attempting to add object to dynamic array causing problems

Hi guys,

I have the following code for a navpoint object in a game which features traffic in a city:

 var connections : GameObject[];

 function Start () {
 
      // TODO: Find 3 closest waypoints facing the same direction, if connections array has no members.
 
      var allWaypoints : GameObject[] = GameObject.FindGameObjectsWithTag("Road Navpoint");
 
      //var waypoints : GameObject[];
  
      var nearestDistanceSqr = Mathf.Infinity; 
      var nearestObj : GameObject = null;
 
      for (var obj : GameObject in allWaypoints) 
      {    
          if (obj.transform.rotation == transform.rotation)
          {
              var objectPos = obj.transform.position;
              var distanceSqr = (objectPos - transform.position).sqrMagnitude;
 
              if (distanceSqr < nearestDistanceSqr) 
              {
                  nearestObj = obj;
                  nearestDistanceSqr = distanceSqr;
              }
         }
     }
     connections[0] = nearestObj;
 }

If a waypoint has had its connections set in the editor, agents use those references when they get to a navpoint and decide where to go next. If they get to a navpoint where no connections have been specified, they go straight for 30m. The idea is to set up one connection (and eventually, three) for navpoints whose connections have not been specified in the editor, using scripting. What I want to do is take the nearest navpoint with the same rotation as an unconnected navpoint and add it to connections[]. However, running the code leads to the following error:

 IndexOutOfRangeException: Array index is out of range.
 (wrapper stelemref) object:stelemref (object,intptr,object)
 CarNavpoint.Start () (at Assets/Game Logic/Scripts/CarNavpoint.js:34)


So the above code throws an out of range exception when trying to add an object to a dynamic array whose size hasn't been specified. What am I missing?

MachCUBED

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 Kryptos · Aug 14, 2012 at 08:14 AM 0
Share

Formatted your code. You can use the "edit" button to do so.

1 Reply

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

Answer by Kryptos · Aug 14, 2012 at 08:06 AM

This is not a dynamic array. You just declared a variable as an array but you didn't create it. Most people think the array is dynamic because you can edit it in the inspector. But in fact the variable is just serialized. So if you didn't specify its size in the inspector, the array will be of size 0.

So it is better to explicitly allocate the array. For example, you can do:

 connections = new GameObject[10];

See the documentation for more details.

Comment
Add comment · Show 4 · 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 MachCUBED · Aug 14, 2012 at 04:35 PM 0
Share

You fixed the assignment problem pretty well. I then discovered that it wasn't checking to see if the array hasn't been initialized yet, so I modified the code like this:

function Start () {

 if (connections == null)
 {
     // TODO: Find 3 closest waypoints facing the same direction, if connections array has no members.

     var allWaypoints : GameObject[] = GameObject.FindGameObjectsWithTag(&quot;Road Navpoint&quot;);

     //var waypoints : GameObject[];
 
     var nearestDistanceSqr = $$anonymous$$athf.Infinity; 
     var nearestObj : GameObject = null;

     for (var obj : GameObject in allWaypoints) 
     {

         if (obj.transform.rotation == transform.rotation)
         {
             var objectPos = obj.transform.position;
             var distanceSqr = (objectPos - transform.position).sqr$$anonymous$$agnitude;

             if (distanceSqr < nearestDistanceSqr) 
             {
                 nearestObj = obj;
                 nearestDistanceSqr = distanceSqr;
             }
         }
     }
     connections = new GameObject[3];
     connections[0] = nearestObj;
     
     Debug.Log("Unpopulated connections array filled");
 }
 else
     Debug.Log(&quot;Pre-existing connections found.&quot;);

}

However, it's not populating the array if it's not set to anything. Is "null" the wrong keyword to use in the initial if statement?

avatar image Kryptos · Aug 16, 2012 at 08:08 AM 0
Share

So if you didn't specify its size in the inspector, the array will be of size 0.

A public variable is automatically serialized. Therefore an array is never null but of size 0 by default. You have to check the size:

 if (connections.Length == 0)

But in order to prevent unnecessary headaches, I recommend to use a mixed check:

 if (connections == null || connections.Length == 0)

It will work in all cases, both with public variables (serialized) and protected or private variables (non-serialized, by default).

avatar image MachCUBED · Aug 16, 2012 at 06:05 PM 0
Share

It's been fixed to look like this:

function Start () {

if (connections == null || connections.Length == 0 || connections[0] == null) { // Find closest waypoint facing the same direction, if connections array has no members.

var allWaypoints : GameObject[] = GameObject.FindGameObjectsWithTag("Road Navpoint");

//var waypoints : GameObject[]; var nearestDistanceSqr = $$anonymous$$athf.Infinity; var nearestObj : GameObject = null;

for (var obj : GameObject in allWaypoints) {

         if (obj.transform.rotation == transform.rotation)
         {
             var objectPos = obj.transform.position;
             var relativePoint = transform.InverseTransformPoint(objectPos);
             
             if(relativePoint.x > 0.0 || relativePoint.x < 0.0)
             {
                 var distanceSqr = (objectPos - transform.position).sqr$$anonymous$$agnitude;

                 if (distanceSqr < nearestDistanceSqr) 
                 {
                     nearestObj = obj;
                     nearestDistanceSqr = distanceSqr;
                 }
             }
         }
     }
     connections[0] = nearestObj;
     
     Debug.Log("Unpopulated connections array filled");

} else Debug.Log("Pre-existing connections found."); }

However, the code for filtering out waypoints that are next to a waypoint when deter$$anonymous$$ing the next waypoint in a sequence:

... if(relativePoint.x > 0.0 || relativePoint.x < 0.0) { var distanceSqr = (objectPos - transform.position).sqr$$anonymous$$agnitude;

                 if (distanceSqr < nearestDistanceSqr) 
                 {
                     nearestObj = obj;
                     nearestDistanceSqr = distanceSqr;
                 }
             }

...

Doesn't appear to be in local space. It seems to be in global space ins$$anonymous$$d. How should it be made into local space?

avatar image Kryptos · Aug 17, 2012 at 07:43 AM 0
Share

That's a new question. Please create a new topic to keep the board clean.

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

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Sequence Scripting 2 Answers

How can I check values of all array/List quickly 1 Answer

I'm trying to sort my Npc's into different social classes 1 Answer

Pair Switch Cases to individual elements in a Vector3 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