Jim*_*m N 1 c# unity-game-engine
编辑:是的,我最近在python中编码,iv混合了两种语言之间的语法.感谢您的改进提示.
我的目标是让if语句工作并输出相应的normal,medium和hard.尽管GameDifficulty设置为2,但它输出的是硬而不是中等.我注意到它只输出最后一个if语句位.它真的很奇怪.
我将GameDifficulty定义为2.当我运行脚本时,Text11变为"硬"而不是"中".我不知道为什么会这样.
谢谢
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class DifficultyDisplayOnWinScreen : MonoBehaviour {
public int GameDifficulty;
public GameObject Text11;
public string diffi;
void Start ()
{
//GameDifficulty = DifficultyChooser.DifficultyNumber;
GameDifficulty = 2;
}
void Update ()
{
//GameDifficulty = DifficultyChooser.DifficultyNumber;
if (GameDifficulty == 3);
{
Text11.GetComponent<Text> ().text = "Normal";
}
if (GameDifficulty == 2);
{
Text11.GetComponent<Text> ().text = "Medium";
}
if (GameDifficulty == 1);
{
Text11.GetComponent<Text> ().text = "Hard";
}
}
}
Run Code Online (Sandbox Code Playgroud)
删除;后面的条件if:
if (GameDifficulty == 3)
{
Text11.GetComponent<Text>().text = "Normal";
}
if (GameDifficulty == 2)
{
Text11.GetComponent<Text>().text = "Medium";
}
if (GameDifficulty == 1)
{
Text11.GetComponent<Text>().text = "Hard";
}
Run Code Online (Sandbox Code Playgroud)
说明:;结束if语句,使其成为空语句.这是因为ifC#中允许使用单行语句,并;确定它们的结束位置.
编辑:我甚至没有注意到;s,是的删除分号,它应该工作.
if (GameDifficulty == 3)
{
Text11.GetComponent<Text>().text = "Normal";
}
if (GameDifficulty == 2)
{
Text11.GetComponent<Text>().text = "Medium";
}
if (GameDifficulty == 1) //if there is only 3 difficulties in this line you can use just else
{
Text11.GetComponent<Text>().text = "Hard";
}
Run Code Online (Sandbox Code Playgroud)
或者使用 if/else
if (GameDifficulty == 3)
{
Text11.GetComponent<Text>().text = "Normal";
}
else if (GameDifficulty == 2)
{
Text11.GetComponent<Text>().text = "Medium";
}
else if (GameDifficulty == 1) //if there is only 3 difficulties in this line you can use just else
{
Text11.GetComponent<Text>().text = "Hard";
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下更好地使用switch/case:
switch(GameDifficulty)
{
case 1:
Text11.GetComponent<Text>().text = "Hard";
break;
case 2:
Text11.GetComponent<Text>().text = "Medium";
break;
case 3:
Text11.GetComponent<Text>().text = "Normal";
break;
}
Run Code Online (Sandbox Code Playgroud)
或者你可以有一个困难字典,例如:
Dictionary<int, string> difficulties = new Dictionary<int, string>()
{
{1, "Hard" },
{2, "Medium" },
{3, "Normal" }
};
Run Code Online (Sandbox Code Playgroud)
并使用它像:
Text11.GetComponent<Text>().text = difficulties[GameDifficulty];
Run Code Online (Sandbox Code Playgroud)
或者enum(有很多方法可以让它更具可读性和简单性,所以我将用这个结束我的例子)
enum Difficulties
{
Hard = 1,
Medium = 2,
Normal = 3
}
Run Code Online (Sandbox Code Playgroud)
用法:
Text11.GetComponent<Text>().text = ((Difficulties)GameDifficulty).ToString();
Run Code Online (Sandbox Code Playgroud)