将int转换为boolean in unity

时间:2016-08-01 06:36:28

标签: c# unity3d

我是团结的新手。 现在这是我的游戏菜单代码:

func(1)=17
func(2)=13
func(3)=17
func(4)=4
...

我尝试运行时遇到此错误:

  

Assets / Scene 1 / s1sc.cs(41,25):错误CS0029:无法隐式转换   输入public class s1sc : MonoBehaviour { private bool toggle2 = false; private bool toggle3 = false; private bool toggle4 = false; private bool toggle5 = false; private bool toggle6 = false; public int maxPlayer = 0; void OnGUI () { if (toggle2 = GUILayout.Toggle (toggle2, "2 player")) { maxPlayer = 2; } if (toggle3 = GUILayout.Toggle (toggle3, "3 player")) { maxPlayer = 3; } if (toggle4 = GUILayout.Toggle (toggle4, "4 player")) { maxPlayer = 4; } if (toggle5 = GUILayout.Toggle (toggle5, "5 player")) { maxPlayer = 5; } if (toggle6 = GUILayout.Toggle (toggle6, "6 player")) { maxPlayer = 6; } if (GUILayout.Button ("mod friendly fire", GUILayout.Width (300), GUILayout.Height (50))) { if (maxPlayer = 0) { GUILayout.TextField ("select max players!", GUILayout.Width (300), GUILayout.Height (50)); } else { Application.LoadLevel ("s2"); } } } } bool'

如何在此代码中将bool转换为int?

4 个答案:

答案 0 :(得分:1)

你不需要。你在if语句中的比较是错误的。

它目前尝试将GUILayout.Toggle (toggle2, "2 player")的结果分配给toggle2,这是一个布尔值。

布尔比较使用双equals符号:像这样:==

请记住,即使您使用双等号,您仍然会尝试将整数与布尔值进行比较。您可以尝试casting or converting the integer以便正确比较它,但最终您可能最好在比较中使用相同的类型。

答案 1 :(得分:1)

您正在使用赋值运算符=,您需要使用比较运算符==

 if (toggle2 == GUILayout.Toggle (toggle2, "2 player")) 
    {
            maxPlayer = 2;
    }

答案 2 :(得分:0)

首先要记住C#是严格的布尔语言 与C ++不同,即

    if(boolean_expression)
    {
       **/*boolean expression should result into either "true" or "false" otherwise 
          you'll get compile time error */**
    }

因为你使用

如果(maxplayer = 0)

" maxplayer = 0"如果你在C ++中使用这个表达式,你将不会得到任何编译错误,0代表C ++中的false和"任何"除零以外的其他值(如1,1.1,"字符串", - 1)将被视为真。

所以使用==这意味着"等于" not =哪个是赋值运算符。

答案 3 :(得分:0)

public class Convert
{
    public static bool intToBool (int Number)
    {
        return (Number == 0 ? false : true);
    }
}