不能“结合”两个变量

时间:2014-01-10 08:53:55

标签: c# unity3d

我正在尝试在游戏引擎中创建一个名为 Unity 的非常简单的弹药脚本。

C#

public int ammoCount = 30;
public string ammoText;

void magazine()
{
    ammoText = "AMMO " + ammoCount + "/30";

    if (Input.GetKey(KeyCode.Mouse0))
    {
        ammoCount = - 1;
    }

    if (Input.GetKey(KeyCode.R))
    {
        ammoCount = 30;
    }
}

所以我想让你关注的是“ammoText =”AMMO“+ ammoCountString +”/ 30“;”。 我在google上搜索过,而且正如我所看到的那样,它应该是应有的。

在我的代码中,我编写了一些代码以使变量出现在屏幕上,但它只显示“AMMO”。

那里有任何答案吗?

先谢谢。

-Mads

编辑:似乎这不是我的剧本。对不起大家!但也许你知道它为什么不显示我的变量?

在屏幕上显示变量的代码:GUI.Label(new Rect(10,10,100,20),(ammoText));

3 个答案:

答案 0 :(得分:2)

你的脚本看起来有点尴尬 - 不完全确定如何调用它或如何将它输出到屏幕上。这是MonoBehaviour中的方法吗?

您可以通过编写Debug.WriteLine(“一些文本或变量”)将调试信息输出到Unity控制台,这将帮助您弄清楚发生了什么。

除了代码有点冗长之外,我认为你要做的事情没有问题,虽然我不确定为什么你想要一个-1或30的值,之间什么也没有。当您按下Mouse0时,您是否尝试从剪辑中删除1个弹药?如果是这样,请使用我在下面发布的代码。我还对代码进行了“改进”,为您提供更多控制。你的一些变量应该是私有的(虽然我不能100%确定你的情况是哪些)因为通过Unity编辑器访问它们没有任何好处。

虽然你的代码可以工作,但是当我在C#中连接时,我倾向于使用string.Concat()或string.Format(),因为它们使事情变得更整洁,并且它们的效率稍高(这是完全是另一个话题。

public int ammoInFullClip = 30;
private int currentAmmoCount = 30;
private string ammoText;

void magazine()
{
    if (Input.GetKey(KeyCode.Mouse0))
    {
        currentAmmoCount-= 1;
    }

    if (Input.GetKey(KeyCode.R))
    {
        currentAmmoCount= ammoInFullClip;
    }

    ammoText = string.Format("AMMO {0}/{1}", currentAmmoCount, ammoInFullClip);
}

<强>更新

使用您的代码,这是 应该工作的完整示例,但我还没有测试过。

public class MyScript : MonoBehaviour {
    public int ammoInFullClip = 30;
    private int currentAmmoCount = 30;
    private string ammoText;

    private void UpdateMagazine() {
        if (Input.GetKey(KeyCode.Mouse0)) {
            currentAmmoCount -= 1;
        }

        if (Input.GetKey(KeyCode.R)) {
            currentAmmoCount = ammoInFullClip;
        }

        ammoText = string.Format("AMMO {0}/{1}", currentAmmoCount, ammoInFullClip);
    }

    public void Update() {
        UpdateMagazine();
    }

    void OnGUI() {
        Debug.WriteLine(ammoText);
    }
}

答案 1 :(得分:0)

要连接字符串和int,如果数字在字符串后面,则不需要使用ToString,只需使用:

ammoText = "AMMO " + ammoCount + "/30";

答案 2 :(得分:0)

您不需要将变量声明为public,只需声明如下

即可

int ammoCount = 30;  string ammoText;

您的连接可以正常运行。

相关问题