![](/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.