• 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
2
Question by Toxic Blob · Mar 08, 2011 at 07:42 PM · javascriptloopdictionaryiterate

Iterate through Generic Dictionary?

How does one iterate through a generic dictionary?

I could find example code in C#, but attempting to adapt it to UnityScript hasn't worked - I get the error Cannot convert 'Object' to 'System.Collections.Generic.KeyValuePair'.

#pragma strict    
static function SetActive( inDict : Dictionary.<String,GameObject>, newState : boolean )
    {
    for(var cObj:KeyValuePair.<String,GameObject> in inDict)
        cObj.Value.active = newState;
    }
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

3 Replies

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

Answer by yoyo · Mar 08, 2011 at 09:33 PM

You can also iterate through the keys (or values) of a dictionary, which might simplify the code. The following samples compile, I haven't tried running them.

By key:

static function SetActive( inDict : Dictionary.<String,GameObject>, newState : boolean )
{
    for(var cKey in inDict.Keys)
        inDict[cKey].active = newState;
}

or by value:

static function SetActive( inDict : Dictionary.<String,GameObject>, newState : boolean )
{
    for(var cObj in inDict.Values)
        cObj.active = newState;
}
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 Toxic Blob · Mar 09, 2011 at 02:22 PM 0
Share

Awesome! With #pragma strict I found it necessary to change the fourth line to (cObj as GameObject).active = newState;

avatar image yoyo · Mar 09, 2011 at 04:40 PM 1
Share

could you say "for(var cObj:GameObject in iDict.Values)"? (I'm not a javascript guy, so I'm making this up as I go along ...)

avatar image
8

Answer by Waz · Jun 05, 2011 at 03:05 AM

The UnityScript foreach statement is not very helpful when you want to use static typing (which you should, it's faster) or generics like this. Instead, fall back to this slightly less pretty enumerator-based syntax:

 for(var e=inDict.GetEnumerator(); e.MoveNext();)
     e.Current.Value.active = newState;

or for clarity:

 var e = inDict.GetEnumerator();
 while (e.MoveNext())
     e.Current.Value.active = newState;

Most importantly, this also works with #pragma strict (which helps you ensure you're writing efficient code), and does not require #pragma downcast.

The basic problem otherwise is that UnityScript's foreach only works with Object subclasses, whereas DictionatyEntry is a value type.

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 drChengele · Jun 16, 2011 at 01:33 PM 0
Share

Thanks for this, it's precisely what I needed. A typesafe way to iterate over dictionary in JS without requiring #pragma downcasts everywhere.

avatar image squidbot · Jun 21, 2011 at 09:01 AM 0
Share

This is definitely a better alternative than the accepted answer! Thanks!

avatar image
1

Answer by Mike 3 · Mar 08, 2011 at 07:50 PM

Fairly odd, but this fixes it:

class Whatever
{
    static function SetActive( inDict : Dictionary.<String,GameObject>, newState : boolean )
    {
        for(var cObj:KeyValuePair.<String,GameObject> in inDict)
            cObj.Value.active = newState;
    }
}

No clue why right now, but with the implicit class it just dies

Edit:

add in #pragma downcast It'll downcast it to the correct type then. Still no clue why

Comment
Add comment · Show 6 · 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 Toxic Blob · Mar 08, 2011 at 08:25 PM 0
Share

That does work, but I don't understand why either. I'm wrapping all the scripts in my utilities into a Utilities class, and now I get that DestroyImmediate isn't a member of Object. This is all very strange...

avatar image Mike 3 · Mar 08, 2011 at 08:29 PM 0
Share

Edited the answer, still no clue but quicker (and more elegant) fix

avatar image Mike 3 · Mar 08, 2011 at 08:30 PM 0
Share

Oh, the DestroyImmediate one I know. Object in js is mapped to System.Object for some bizarre reason. If you use GameObject.DestroyImmediate, it should fix that

avatar image Toxic Blob · Mar 08, 2011 at 08:56 PM 0
Share

Okay, it seems that if this function is in any class that is called by another class, then I get the "Cannot convert 'Object'..." error.

avatar image Mike 3 · Mar 08, 2011 at 09:05 PM 0
Share

You'll probably need to use #pragma downcast to those too. This seems like a compiler error to be honest

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

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

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

Referencing the object that a construtor is currently constructing/working on. 1 Answer

JS Loop question 2 Answers

Find Position in Array or List? 2 Answers

Compilor Error using Dictonary collection 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