如何在 Unity 中打印从脚本化对象中随机选择的字符串?
How to print a randomly selected string from Scriptable Objects in Unity?
我想从可编写脚本的对象中随机选择一个项目,然后将随机选择的项目打印到控制台。
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];
}
您可以像这样覆盖 class 的 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());
输出应该类似于:"Name : Canada Currency: CAD Capital: Ottawa Cities: Toronto, Montreal, Vancouver."。
您可以随意调整输出。
我想从可编写脚本的对象中随机选择一个项目,然后将随机选择的项目打印到控制台。
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];
}
您可以像这样覆盖 class 的 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()); 输出应该类似于:"Name : Canada Currency: CAD Capital: Ottawa Cities: Toronto, Montreal, Vancouver."。 您可以随意调整输出。