繁体   English   中英

错误CS0029:无法将类型'int'隐式转换为'Score'

[英]error CS0029: Cannot implicitly convert type 'int' to 'Score'

我搜索了一段时间,无法找到答案,希望有人可以帮助我! 我想做的是保存我的分数并将其转移到另一个场景。 有了这段代码,我在这里得到错误:

错误CS0029:无法将类型'int'隐式转换为'Score'

我对统一脚本也很陌生。

这是我正在使用的两个脚本

脚本1 Score.cs

using UnityEngine;
using System.Collections;

public class Score : MonoBehaviour {

    static public int score = 0;
    static public int highScore = 0;

    static Score instance;

    static public void AddPoint() {
        if(instance.run.dead)
            return;

        score++;

        if(score > highScore) {
            highScore = score;
        }
    }
    Running run;

    void Start() {
        instance = this;
        GameObject player_go = GameObject.FindGameObjectWithTag("Player");
        if (player_go == null) {
            Debug.LogError("could not find an object with tag 'Player'.");
        }
        run = player_go.GetComponent<Running> ();
        score = 0;
    }

    void OnDestroy() {
        PlayerPrefs.SetInt ("score", score);
    }

    void Update () {
        guiText.text = "Score: " + score;
    }
}

第二个脚本将其转到另一个场景

using UnityEngine;
using System.Collections;

public class GetScore : MonoBehaviour {

    Score score;

    // Use this for initialization
    void Start () {
        score = PlayerPrefs.GetInt ("score");

    }

    // Update is called once per frame
    void Update () {
        guiText.text = "Score: " + score;

    }
}

非常感谢任何帮助!

score = PlayerPrefs.GetInt ("score");

该错误是由上述行引起的。 名称说明中的PlayerPrefs.GetInt将返回一个整数。 现在看看如何声明score变量:

Score score;

这导致变量score具有类型Score类,而不是int类型。

我想您想在Score类中设置变量score 由于您将可变score声明为static public ,因此事情变得容易。 您不必创建Score的实例,只需使用类名称Score (大写S)代替:

Score.score = PlayerPrefs.GetInt("score");

PLayerPrefs.GetInt将返回一个int但您放置了一个Score类克隆以将PLayerPrefs.GetInt的返回值分配给它,因此int不能成为Score因此如果您要访问score类变量,则应执行此操作

void Start () {
    score=score.GetComponent<Score>();
    score.score = PlayerPrefs.GetInt ("score");

}

因为您的分数可变性是static您也可以使用它

 void Start () {

    Score.score = PlayerPrefs.GetInt ("score");

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM