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 Muzz5 · Sep 07, 2011 at 07:20 AM · arrayvectoroutofbounds

Find the average of 10 Vectors

I'm trying to find the average of 10 Vector3s, using the following script.

 var positions = new Array();
 var pos2 = new Array();
 var diameter = 3.0;
 var numberOfPoints = 10;
 var pointObject : Transform;
 var n = 0;
 var m = Vector3.zero;
 var o = Vector3.zero;
 var p = new Array ();
  
 private var point : Vector3;
 
 function Start () {

 direction();
 }
 
 
 function direction(){
 var q = Vector3.zero;
 for (i=0; i<numberOfPoints; i++){
 positions[i] = m;
 positions[i++] = o;
 p.Push[m+o];
 }
 }

Positions is an array which contains the vectors. I get an 'array is out of bounds' error.

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 Kiloblargh · Dec 03, 2013 at 04:46 PM 0
Share

Why on earth are you using Array()? All I've ever heard about the Array class is "It's slow, don't use it." List's are usually better, unless you never add or remove anything in which case you use the Vector3[] type of array.

4 Replies

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

Answer by CHPedersen · Sep 07, 2011 at 08:53 AM

Much of that loop is wrong, I'm afraid. :P

Thor is correct that you're getting the exception because you've incremented i to a number greater than the length of the Array-1, but he's wrong to say that the loop must run while i is less than numberOfPoints-1. Because arrays are zero-indexed, accessing an element at the index i is valid as long as i is less than the length (and greater than or equal to 0), not length-1.

In general, it's bad form to use constant numbers as the limit of array iteration, unless you can be perfectly sure your array's runtime length never deviates from that number. It's always better to use Array.length as the limit in the loop instead of some integer you've set.

In addition to these facts, be mindful of changing your iterator (i) inside the loop: You've got code that says positions[i++] inside the loop body. This can be dangerous business and generally shouldn't be done unless you're absolutely sure about what you're doing. As you know, i++ is short-hand for i = i + 1;, so if you increment i there, then i will get incremented again by the for-loop on the next iteration, causing you to effectively skip an element in the array.

Finally, if the 'average' you want is a single vector that points in the direction you'd be headed if you followed each of the component vectors one by one, the result is just the sum of all the component vectors. Here's a snippet that does that:

 Vector3[] vectors = new Vector3[10];

 Vector3 average = Vector3.zero;

 for (int i = 0; i < vectors.Length; i++)
 {
     average += vectors[i];
 }

Translation to JS is a pretty straight forward. :)

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 sarahnorthway · Jun 08, 2016 at 07:14 PM 3
Share

Don't forget to divide the average by the number of Vector3s: average /= vectors.Length;

avatar image
8

Answer by grofie · Dec 03, 2013 at 03:31 PM

All previous posts forget to divide through the number of entries.

Try this piece of code:

 private Vector3 GetMeanVector(Vector3[] positions)
 {
     if (positions.Length == 0)
         return Vector3.zero;
     float x = 0f;
     float y = 0f;
     float z = 0f;
     foreach (Vector3 pos in positions)
     {
         x += pos.x;
         y += pos.y;
         z += pos.z;
     }
     return new Vector3(x / positions.Length, y / positions.Length, z / positions.Length);
 }


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
1

Answer by marinbenc · Mar 28, 2020 at 08:15 AM

Another single-line option using LINQ:

 List<Vector3> vectors = ...  
 var averagePosition = vectors.Aggregate(Vector3.zero, (acc, v) => acc + v) / vectors.Count;
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 thor_tillas · Sep 07, 2011 at 07:45 AM

As far as I understand, you have to do your loop as long as i is under numberOfPoints - 1 instead of numberofPoints. Otherwise, the line

 positions[i++] = o;

while raise a "Out of bounds" exception.

But this works only when your "Position" array is initialized with "numberOfPoints" position...

Hope it's helped !

Cheers, Thor

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

7 People are following this question.

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

Related Questions

Filling an array with child vectors 2 Answers

How to check if vector in array was not changed? 1 Answer

Getting all objects with a tag and inserting them into an array of gameobject 1 Answer

Array "size" question. 1 Answer

How do I make an array of vectors? 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