2014-09-25 162 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"); 

} 
相關問題