![](/img/trans.png)
[英]Unity not destroying ontriggerenter2d object with TypeFruit
[英]Unity - How to add score after destroying object in unity 2D?
在此之前,我為我的程序制作了一個評分部分,使用Invoke重復每1秒。 現在,我有問題如何在我銷毀某些對象時讓我的得分計數器添加額外的分數。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
public Button[] buttons;
public Button pauseButton;
public Image[] images;
public Text scoreText;
public Text highScoreText;
public Text yourScoreText;
public Text text;
bool gameOver;
int score;
levelscroller level;
CoinMove cm;
void Start()
{
gameOver = false;
score = 0 + cm.plus;
InvokeRepeating("scoreUpdate", 1.0f, 1.0f);
}
void Update()
{
storeHighScore(score);
scoreText.text = "" + score;
yourScoreText.text = "" + score;
highScoreText.text = "" + PlayerPrefs.GetInt("highscore");
}
void scoreUpdate()
{
if (gameOver == false)
{
score += 1;
}
}
void storeHighScore(int newHighscore)
{
int oldHighscore = PlayerPrefs.GetInt("highscore", 0);
if (newHighscore > oldHighscore)
{
PlayerPrefs.SetInt("highscore", newHighscore);
oldHighscore = newHighscore;
PlayerPrefs.Save();
}
}
另一課:
using UnityEngine;
using System.Collections;
public class CoinMove : MonoBehaviour
{
public float Speed;
public int plus = 0;
UIManager ui;
void Start()
{
}
void Update()
{
transform.Translate(new Vector3(0, -1, 0) * Speed * Time.deltaTime);
//if (Input.touchCount > 0 || Input.GetTouch(0).phase == TouchPhase.Began)
//{
// Destroy(transform.gameObject);
//}
}
private void OnMouseDown()
{
Destroy(gameObject);
plus += 10;
}
}
它只是使得分的計數器完全為0而不是增量。
我真的沒有得到你背后的邏輯int plus
值和引用CoinMove cm
和UIManager ui
...
實現您正在嘗試的最簡單方法是在CoinMove腳本中使用UIManager ui
簡單地引用您的UIManager ,向UIManager添加一個新方法:
public void AddScore(int scoreToAdd)
{
score += scoreToAdd;
}
然后,當您想要在CoinMove腳本中銷毀硬幣時,請在銷毀對象之前調用此方法:
private void OnMouseDown()
{
ui.AddScore(plus);
Destroy(gameObject);
}
希望這可以幫助,
首先:
不要在每一幀使用PlayerPrefs,在幕后,unity使用IO來保存文件。 你想在游戲結束時保存高分。
在UIManager中,你將管理得分遞增。 實際上,最好的做法是在控制器中處理Score增量(比如名為GameController的類),因此UI腳本只有映射函數(例如,值為文本字段)。 通過拆分控制器和UI,您可以更輕松地擴展和更改內容。
為了簡單起見,我們忽略了我認為更簡潔的編程版本。
每個持有分數值的對象都可以添加到腳本中(在您的示例中,它的CoinMove):
public int scoreValue;
這可以在檢查器中配置為您想要的任何值,或者如果您願意,可以為其指定標准值。
CoinMove應該有以下方法:
public void AddScore(int amount) {
score += amount;
}
因為您在CoinMove中引用了UIManager,所以在coinMove中我們可以這樣做:
private void OnMouseDown()
{
Destroy(gameObject);
ui.AddScore(scoreValue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.