Search code examples
c#visual-studiounity-game-enginescriptable-object

How to print a randomly selected string from Scriptable Objects in Unity?


I want to randomly pick an item from a scriptable object and then print the randomly chosen item to the console.

 using System.Collections;
   using System.Collections.Generic;
   using UnityEngine;  

   [CreateAssetMenu(fileName = "Country", menuName = "Country/Country", order = 0)]
   public class country : ScriptableObject
   {
       [System.Serializable]
       public class Item
       {
           public string Name;
           public string Currency;
           public string Capital;
           public string[] City;

       }
       public Item[] m_Items;
   }

How do I go on printing the following values to the console?

  public Item PickRandomly()
  {
      int index = Random.Range(0, m_Items.Length);
      return m_Items[index];
  }

Solution

  • You can override the ToString() function for your class like so.

     [System.Serializable]
           public class Item
           {
               public string Name;
               public string Currency;
               public string Capital;
               public string[] City;
    
                public override string ToString()
                {
                    string toPrint = "Name: " + this.Name + " Currency: " + this.Currency + " Capital:" + this.Capital;
                    if(City != null)
                    {
                        toPrint += " Cities: ";
                        for(int  i =0; i < City.Length; ++i)
                        {
                            toPrint += City[i];
                            if(i < City.Length -1)
                            {
                                toPrint += ",";
                            }
                            else
                            {
                                toPrint += ".";
                            }
                        }
                    }
                    return  toPrint;
                }
           }
    

    After that you can simply call Debug.Log(PickRandomly()); The output should be something like : "Name : Canada Currency: CAD Capital: Ottawa Cities: Toronto, Montreal, Vancouver.". You can tweak the output anyway you prefer.