• 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 evilpikmin · Oct 03, 2013 at 10:05 PM · javascriptarraysoverlapsphere

Searching through an Array

Hi, I am trying to search through my objects to create another array comtianing just the objects called 'waypoint01', 'waypoint02' etc When I use this:

 function Start ()
 {
     var InRange : Collider[] = Physics.OverlapSphere(transform.position, 10);
         for (var i = 0; i < InRange.length; i++){
         Debug.Log(InRange[i]);
     }
     
         
     for (n=0; n < InRange.Length; n++){
         if (InRange[n] == "waypoint03")
             Debug.Log("You found waypoint03!");
             }
     
 var search = function(Waypoint01){
     for(var i in InRange){
         if(InRange[i] == Waypoint01){
             Debug.Log(InRange[i]);
             }
         }
     };
             
 }

Unity then complains that:

Assets/scripts/overlapsphere.js(16,9): BCE0022: Cannot convert 'UnityEngine.Collider' to 'int'.

So can anyone tell me how I can convert it to 'int' or whether I am just going about this all wrong.

Cheers

Comment
Add comment
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

1 Reply

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

Answer by Hoeloe · Oct 03, 2013 at 10:11 PM

You're trying to use a foreach loop as though it is a regular for loop. The foreach loop (in Javascript, this looks like for(var i in Array)) does not use the index of the array as its argument, but the value in the array. When you write for(var i in InRange){, the variable i is not assigned to the index in turn (i.e. 0,1,2... etc), but the value (i.e. InRange[0], InRange[1]... etc). This means that when you write InRange[i] on the next line, you are essentially writing: InRange[InRange[0]], which throws a type error because you can't index an array with a Collider. To further demonstrate this, I will convert your last loop into the other kind of for loop, to demonstrate what it is trying to do:

 var search = function(Waypoint01)
 {
     for(var i = 0; i < InRange.length; i++)
     {
         if(InRange[InRange[i]] == Waypoint01)
         {
             Debug.Log(InRange[InRange[i]]);
         }
     }
 };

This code will execute in almost exactly the same way as yours, and will throw the same error. I hope you can see the problem with it.


IN RESPONSE TO YOUR COMMENT


No, absolutely not. You've gone worse, if anything, because it's now not even syntactically correct.

Let me teach you the basics of a for loop. A for loop is very similar to a while loop (in fact, under the hood, all for loops are while loops), but with the difference that they retain some information between passes of the loop. The structure of a for loop is like this:

 for(assign variable starting value; conditions under which to continue; action to perform after each pass)

The most common for loop is the counting loop, which is usually written like so:

 for(var i = 0; i < 10; i++)

So, reading this out, it says that, before starting the loop, we create a variable, to which we assign the value 0. Then, we test the conditions - is the variable i less than 10? Since i is 0, this returns true, and we execute the loop. When the end of the pass is finished, it runs the actions (i++), which adds one to the variable i, and starts again (from the point where we tested the conditions). This in itself is pretty useless, but since the conditions are arbitrary, you can substitute a variable in for the 10. Most commonly, this is the length of an array.

Now, you need to take into account types here. Javascript is not a strongly typed language (and actually, this makes it bad for beginners, because it can make for some very confusing code), but here it's pretty clear that i is of type int. When indexing arrays, you use an integer value, so this is fine for indexing into arrays, in the same way you would write Array[0], writing Array[i] is perfectly valid. Remember, the variable defined in a for loop is not special, it behaves just like any other variable.

So, let us take an example of operating on an array called array, containing the elements: 10, 9, 8, 7 and 6.

 for(var i = 0; i < array.Length; i++)
 {
     Debug.Log(i + " : " + array[i]);
 }

This will print out:

 0 : 10
 1 : 9
 2 : 8
 3 : 7
 4 : 6

Note that i is the position of the element in the array, while array[i] is the actual element at that position (also, it's worth noting that arrays are 0-indexed, meaning the first element is at index 0).

Now, let us talk about the foreach loop. This is actually just an abstraction for a specific kind of for loop. Foreach loops are written like this:

 for(new variable in array)

This allows the loop to iterate through an array, returning the value of the array as the variable of the loop. This is essentially the same as the previous example, but now we can't easily access the index of the element we're looking at - we just get the actual element, so we can't use this for counting to arbitrary numbers any more, but we can use it to shorten our previous example:

 for(var t in array)
 {
     Debug.Log(t);
 }

(Note that I've called the variable t here, not i. The name is not actually important, but by convention, i is reserved for the index of an array, and that is not what we're looking at). This will print out, given the same array as before:

 10
 9
 8
 7
 6

Note that this time, even through we're printing out the variable directly from the loop, we get the elements of the array, not the indices. Thus, the type of t here is not necessarily int. The type of this variable depends on the type of the array. In this example, I had an array of ints, so the type of t would also be int, but if I replaced it with an array of floats, then the type of t would be float.

Now, I want to say one last thing on foreach loops. I mentioned that they were an abstraction, well, that's because they are actually just a shorthand way of writing this (to use the above loop for comparison):

 for(var i = 0; i < array.Length; i++)
 {
      var t = array[i];
      Debug.Log(t);
 }

This is actually identical to the foreach loop I wrote above (and hopefully you can start to see why I didn't call the temporary variable i).

So, key points to take away:

  • for loops are designed to loop and hold the state of a variable while they do.

  • foreach loops are specifically designed for iterating through arrays and collections.

  • The variables defined in for loops are not special - they are the same as any other variable.

  • The syntax for using these variables is the same as any other variable.

Comment
Add comment · Show 8 · 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 evilpikmin · Oct 03, 2013 at 10:51 PM 0
Share

Great answer thanks. what I thought was going to work didnt, am I on the right track?

 var search = function(Waypoint01)
 {        
     for (var n=0; n < InRange.Length; n++){
         if ([n] == waypoint03){
             Debug.Log("You found waypoint03!");
             }
         }
     };
 }
avatar image Hoeloe · Oct 03, 2013 at 11:24 PM 0
Share

I'm going to have to post my response as another answer, because I ran out of characters.

avatar image evilpikmin · Oct 05, 2013 at 07:03 PM 0
Share

O$$anonymous$$ thats a lot clearer now, thank you! But I am just not understanding how to search through my array. I have used both methods here and they both list what I need, but obviously I am missing something with my search function as it prints nothing. If you can help me some more that would be great. Thanks in advance.

 function Start ()
 {
     var InRange : Collider[] = Physics.OverlapSphere(transform.position, 10);
         for(var wp in InRange){
         Debug.Log(wp);
         }
         
         
         for(var i=0; i<InRange.Length; i++){
         Debug.Log(InRange[i]);
         }
         
         if(InRange == "waypoint01"){
             Debug.Log("you found waypoint01");
             }
         
 }
avatar image tw1st3d · Oct 05, 2013 at 07:06 PM 1
Share

This is an amazingly thorough answer, that I'm sure will help many new programmers. +1

avatar image Hoeloe · Oct 05, 2013 at 07:35 PM 1
Share

@evilpik$$anonymous$$: You really need to study up some basic program$$anonymous$$g concepts. If you had any idea what you were typing, you would see immediately why that was wrong. Take some beginner tutorials - you'll hit some serious walls otherwise.

Show more comments

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

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

Distance error: Cannot cast from source type to destination 0 Answers

Physics: Is it possible to count the number of colliders hit with OverlapSphere? 1 Answer

Type function(): Object[] does not support Slicing 1 Answer

Change rigidbody values on mutliple objects (ARRAY) 1 Answer

hit.rigidbody.useGravity problem? 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