Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将字符串(位置)转换为int?_C# - Fatal编程技术网

C# 如何将字符串(位置)转换为int?

C# 如何将字符串(位置)转换为int?,c#,C#,我收到编译错误:无法将类型“string”隐式转换为“int” { public Transform player; public Text scoreText; // Update is called once per frame void Update() { int score = player.position.z.ToString("0"); scoreText.text = score.ToString();

我收到编译错误:无法将类型“string”隐式转换为“int”

{
    public Transform player;
    public Text scoreText;

    // Update is called once per frame
    void Update()
    {
        int score = player.position.z.ToString("0");
        scoreText.text = score.ToString();
    }
}
player.position.z是一个浮点数,请参见矢量3。因此,现在您正试图将这个浮点值转换为int,但您使用的是toString方法,该方法将浮点值转换为字符串。这不起作用,因为不能将int的值设置为字符串之一

可以通过强制转换将浮点转换为int:

int score = (int) player.position.z;
或者使用Unity的舍入方法:


我猜你在使用统一。这里是一个浮点数。看起来你要做的是把那个浮点数转换成字符串。然后将其转换为int,然后再次将其转换为字符串

因为您需要的是一个字符串,所以可以直接从float转到如下所示的字符串:

{
    public Transform player;
    public Text scoreText;

    // Update is called once per frame
    void Update()
    {
        scoreText.text = player.position.z.ToString("0");
    }
}

哪行代码出现错误?int.Parseplayer.position.z.ToString0或使用TryParse。但是如果你需要它作为一个字符串,为什么要把它改成int呢?哦,很抱歉忘了提到这一点,下面的行int score=player.position.z.ToString0;ToString只返回字符串,而不是int。我想您可以完全忽略score变量,只使用scoreText.text=player.position.z.ToString G0;。z是一个浮点数,所以你要做很多不必要的工作,把它变成一个字符串,然后把它转换成一个整数。您可以将其转换为如下整数:int score=intplayer.position.z;
{
    public Transform player;
    public Text scoreText;

    // Update is called once per frame
    void Update()
    {
        scoreText.text = player.position.z.ToString("0");
    }
}