【问题标题】:MORE scripting problems in Unity C#Unity C# 中的更多脚本问题
【发布时间】:2015-06-25 17:34:37
【问题描述】:

备份我之前回答的问题 (Displaying variables using gui in Unity),我需要一些帮助来解决更多问题!我收到一个错误提示

无法将类型 string 隐式转换为 bool。

这是我使用的(改编的)代码:

using UnityEngine;
using System.Collections;
public class ConnectGUI : MonoBehaviour {
//Variables
string Map;
string Gamemode;
//Var set
void Start () {
    Map = "No map selected!";
    Gamemode = "No game mode selected!";
}
//Configurable settings.
void OnGUI () {
    //Map GUI
    GUI.Box(new Rect(10,10,200,90), "Map selected: "+ Map);
    if(GUI.Button (new Rect(10,50,90,20), "Pier")){
        Map = "Pier";
    }
    //Game mode GUI
    GUI.Box (new Rect(350,10,250,90), "Mode selected: "+ Gamemode);
    if(GUI.Button (new Rect (375,50,125,20), "Team Deathmatch")){
        Gamemode = "Team Deathmatch";
    }
}
//ConnectToServer
void Connect () {
    if (Map = "Pier"){
        if (Gamemode = "Team Deathmatch") {
            Application.LoadLevel("Pier TeamDM");
        }
    }

}

}

有解决这个错误的想法吗?

P.S:如果您想知道为什么不调用 connect() 函数,那是因为它是通过 unity 的新 UI 系统调用的。

【问题讨论】:

  • 您尝试分配字符串的 bool 属性位于哪一行?
  • 包括堆栈跟踪。哪一行导致了错误。
  • 能否给我们完整的错误信息,尤其是上面哪几行抛出了异常。

标签: c# unity3d error-handling


【解决方案1】:

你打错了。 Map = "Pier" - 将值 "Peir" 分配给变量 Map。应该 地图==“皮尔”。但是要比较你持有的字符串,请使用 String.Equals

void Connect () {
if (Map.Equals("Pier")){
    if (Gamemode.Equals( "Team Deathmatch")) {
        Application.LoadLevel("Pier TeamDM");
    }
}

【讨论】:

  • 我相当肯定 C# 重载了“==”运算符,因此您不必像在 Java 中那样调用 .Equals
  • 你正确的 C# 重载。但是使用 String.Equals 可以让您在使用嵌套 if 做出决定并且输入字符串变量之一将为空时捕捉到一种情况。如果你使用 == 你会有奇怪的行为,如果你使用 String.Equals 你会有一个异常。 BTW 有时比 == 快。
  • @vsenik 我将在未来编码时记住这些提示(针对 Unity C#)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多