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
1
Question by Sottnik · May 09, 2017 at 05:44 AM · c#script.randomdictionaryelement

Display random element from dictionary

Hi everyone, I need your help I want to pick up random element from dictionary and display this element’s key and valeu in different UI Texts. Until now I figured up just how to display random value. Thanks for your help.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System.Linq;
 using UnityEngine.UI;
 
 public class ListManager : MonoBehaviour {
 
    // public string car;
   //public int speed;
     public Text keyText;
     public Text valueText;
     Dictionary<string, int> database = new Dictionary<string, int>();
    
 
 
 
     // Use this for initialization
     void Start () {
         AddToDatabase();
         ShowRandomElement();
     }
     
     // Update is called once per frame
     void Update () {
         
     }
 
    
     public void ShowRandomElement()
     {
         
         var randomKey = database.Keys.ToArray()[(int)Random.Range(0, database.Keys.Count - 1)];
         var randomValueFromDictionary = database[randomKey];
         valueText.text = randomValueFromDictionary.ToString();
         foreach (KeyValuePair<string,int> item in database)
         {
             Debug.Log ("Key: "+item.Key+","+"Item: "+item.Value);
         }
 
 
     }
 
 
     public void AddToDatabase()
     {
         database.Add("Lamborghini Veneno", 350);
         database.Add("Bughatti Veyron", 420);
         database.Add("Porchce Carera", 400);
         database.Add("Hennesey GT", 460);
         database.Add("MCLaren P1", 370);
         database.Add("MCLaren F1", 430);
     }
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 Kshesho · Jun 26, 2020 at 03:39 AM 0
Share

Thanks for this post. I didn't know about the ToArray() function.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by RodrigoAbreu · Jun 26, 2020 at 04:48 AM

Hey @Sottnik, what is up!? So, I'm guessing you're wanting to have a different new UI text element for each of the new values you're randomizing.

So:

  1. Remove those text elements from this class

  2. Create a new class (also Monobehaviour) holding only those two elements, call it maybe something like TextWidget or something like that.

  3. Expose some method to pass those two strings, maybe a setter where you'll pass those 2 strings and then in that setter you'll just set those strings into the Text.text.

  4. Create a new object in your hierarchy.

  5. Add that new TextWidget (Or whatever you call it) to that new object.

  6. Drag this object to your Project window to create a prefab out off it.

  7. Now in your ListManager class add an entry, a new reference to that widget type, and pass the prefab to it through inspector.

  8. In your method "ShowRandomElement", now instantiate (or use an object pool if you really need more in runtime) and pass those strings to that object's setter as I said above.

  9. Remember to set your instance of "TextWidget" to have the proper parent (The correct canvas where you intend to display those elements) textWidgetInstance.transform.SetParent(PASS_YOUR_CANVAS_TRANSFORM_HERE)

And I guess that's it.

Tip: Avoid iterating through hash structures like dictionaries, they tend to get slower for iteration as it grows in elements. If you need to keep growing that dictionary, please consider creating some logic with a dictionary and a list, maybe a list of your keys (strings) and then you'd be able to randomize one of those keys and then use that key to tryGet the value from the dictionary. That way you'd just need to randomize an int considering the size of that list, then use a list[index] to retrieve the string key, use that string key to tryGetting your value and you're good.

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

8 People are following this question.

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

Related Questions

Distribute terrain in zones 3 Answers

how can i check if there is a blanc spot in my list 3 Answers

Generate a big digit with only 1 2 3 and 4,How to generate a big number that only countains 0 to 3 2 Answers

Multiple Cars not working 1 Answer

dictionary, random element (js) 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