2014-09-25 157 views
1

我已经搜索了一段时间,无法找到并回答希望有人能帮助我!我想要做的是保存我的分数并将其转移到不同的场景。有了这个代码,我这里有我的错误:错误CS0029:无法将类型'int'隐式转换为'Score'

错误CS0029:Cannt隐式转换类型“诠释”到“分数”

我是相当新的统一的脚本为好。

这里有两个脚本我使用

脚本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; 

    } 
} 

非常感谢所有帮助!

+0

不能在代码片段工具运行C#代码。这是为JavaScript,HTML和CSS。 – 2014-09-25 07:32:28

+0

是的,请不要将Stack Snippet用于非JS/HTML/CSS代码,我已将其删除。 – 2014-09-25 07:33:57

回答

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

错误是由上面的行引起的。 PlayerPrefs.GetInt,因为它的名称状态将返回一个整数。现在看你怎么声明score变量:

Score score; 

这将导致变量scoreScore型类,而不是int

我想你想在Score类中设置变量score。由于您将变量score声明为static public,这使事情变得简单。您不必创建的Score一个实例,只需要使用类名Score(资本S)代替:

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

好的,谢谢你的帮助,我做了你所说的事情。我不再有错误,这是一件好事!但是在deathScene中并没有显示分数分数是否在“0”处,为什么它会这样做呢? – GeneralVirus 2014-09-25 07:53:17

+0

尝试在'OnDestroy()'中打印'score'的值,我们将看看是否调用了该函数,以及分数是否正确递增。 – 2014-09-25 08:00:43

+0

你打电话给AddPoint – 2014-09-25 08:12:03

2

PLayerPrefs.GetInt将返回一个int,但你把一个Score类的clone分配的 PLayerPrefs.GetInt它,int返回值着成为Score,所以如果你要访问的比分类变量,你应该这样做

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

} 

因为你的分数varaible是static你可以使用这个太

void Start() { 

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

} 
相关问题