Debug.Log和Debug.LogFormat
Debug.Log和Debug.LogFormat都是Unity中常用的输出调试信息的方法,它们的主要区别在于将变量插入到输出文本中的方式不同。
Debug.Log方法接受一个字符串参数,该字符串表示要输出的文本。例如:
csharpCopy Code
Debug.Log("The player's health is 50.");
这会将"The player's health is 50."输出到Unity控制台中。
而Debug.LogFormat方法则接受两个参数:第一个参数是一个字符串,包含了格式化字符串中的占位符;第二个参数是一个可选参数列表,包含要插入到格式化字符串中的值。例如:
int health = 50;
Debug.LogFormat("The player's health is {0}.", health);
这会将"The player's health is 50."输出到Unity控制台中。
在上面的示例中,字符串"The player's health is {0}."中的"{0}"表示一个占位符,它将被后面的health变量替换。这个占位符的索引为0,因此在第二个参数列表中,我们需要将health变量传递给索引为0的位置。
列表
void Start()
{
List<string> questPartyMembers = new List<string>()
{"Grim the Barbarian","Merlin the Wise","Sterling the King" };
Debug.LogFormat("Party Members:{0}",questPartyMembers.Count);
}
questPartyMembers.Count 函数统计这个列表的数量。
字典
是一种键值对(key-value pair)的数据结构。它提供了一种快速查找和获取值的方式,通过使用键来索引值。
void Start()
{
Dictionary<string,int> itemInventory =new Dictionary<string,int>(){
{"Potion",5},
{"Antidote",7},
{"Aspirin",1}
};
Debug.LogFormat("Items:{0}",itemInventory.Count);
}
定义一个字典,并且统计字典键值对数量
注意,键值对里面只能有两个类型,不能有多个。
迭代语句
For循环
List<string> questPartyMembers = new List<string>()
{"Grim the Barbarian","Merlin the Wise","Sterling the Knight"};
for(int i=0;i<questPartyMembers.Count;i++){
Debug.LogFormat("Index:{0}-{1}",i,questPartyMembers[i]);
if (questPartyMembers[i]=="Merlin the Wise")
{
Debug.Log("Glad you're here Merlin!");
}
}
Foreach
foreach
是C#中的一种迭代循环结构,用于遍历集合中的元素。
下面是一个示例代码,演示如何使用foreach
来遍历字典中的键值对:
void Start()
{
Dictionary<string, float> itemInventory = new Dictionary<string, float>()
{
{"Potion", 11.2f},
{"Antidote", 11.3f},
{"Aspirin", 11.5f}
};
foreach (KeyValuePair<string, float> item in itemInventory)
{
string itemName = item.Key;
float itemWeight = item.Value;
Debug.LogFormat("Item: {0}, Weight: {1}", itemName, itemWeight);
}
}
While
{
int playerLives=3;
while(playerLives>0){
Debug.Log("仍旧存活");
playerLives--;
}
Debug.Log("Player KO");
}