0

我想从可编写脚本的对象中随机选择一个项目,然后将随机选择的项目打印到控制台。

 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;
   }

如何继续将以下值打印到控制台?

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

1 回答 1

0

您可以像这样覆盖您的类的 ToString() 函数。

 [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;
            }
       }

之后,您可以简单地调用 Debug.Log(PickRandomly()); 输出应类似于:“名称:加拿大货币:CAD 首都:渥太华城市:多伦多、蒙特利尔、温哥华。”。您可以随意调整输出。

于 2020-04-02T16:12:40.857 回答