c# - Unity 2018 - UI 文本元素 - 拾取时不更新计数
问题描述
我的问题是该代码仅适用于玩家触摸的第一个项目(星形平板电脑)。之后,数字将保持为 1。我怀疑我的 Destroy() 函数擦除了脚本并且必须忘记计数?但是,我不知道可以采取任何替代措施。如果我对此有误,请告知我出了什么问题以及我需要采取哪些步骤来解决它。这是我的整个脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StarTabletScript : MonoBehaviour
{
public static GameObject starTab; // The actual Star Tablet gameobject - May need to use in other script later?
private int starTabCount = 0; // Counts total stars in the scene
private int starTabCollected;// Star off with zero star tabs collected
private GameObject[] starTabTotal; // Reads the total amount of star tabs in the scene
public Image starImg; // The star sprite
public Text starTxt; // The star Text
[SerializeField]
private Renderer starMesh; // Used to deactivate the mesh of the star tab upon collision
void Start()
{
starTab = GetComponent<GameObject>();
starTabCollected = 0;
starTabTotal = GameObject.FindGameObjectsWithTag("StarTab");
foreach (GameObject star in starTabTotal)
{
starTabCount++;
}
StartCoroutine(StartShow()); // Shows image upon start
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
starMesh.enabled = false;
StartCoroutine(ShowStar());
}
}
IEnumerator ShowStar() // Shows star image on pickup
{
starTabCollected++;
Debug.Log("3) Stars collected "+starTabCollected);
starImg.enabled = true;
starTxt.enabled = true;
starTxt.text = starTabCollected + " / " + starTabCount;
yield return new WaitForSeconds(3);
starImg.enabled = false;
starTxt.enabled = false;
Destroy(gameObject);
}
IEnumerator StartShow() // Shows star on program start
{
Debug.Log("1) Total Stars in scene "+starTabCount);
Debug.Log("2) StarTab.Length testing "+starTabTotal.Length);
starImg.enabled = true;
starTxt.enabled = true;
starTxt.text = starTabCollected + " / " + starTabCount;
yield return new WaitForSeconds(5);
starImg.enabled = false;
starTxt.enabled = false;
}
}
解决方案
您在场景中有三个脚本副本
每个副本都有这个:
private int starTabCollected;
这意味着你拿起的每一个总是第一个。
推荐阅读
- android - 未解决的参考:build.gradle.kts 中的 grgit
- java - 修改已经存在的bean
- c# - Xamarin 形式 最多一个元素
应使用命名空间“” - reactjs - Kubernetes/Docker/Create React App + nginx 不返回静态文件?
- java - 如何在 Java 中精确计算距离?
- sql-server - SQL Server:数据库用户访问模式
- java - 组件 tJavaFlex_1(时间)中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 javatflex 和 tmemorizerows
- tensorflow - Tensorflow:对 LSTM 的期望
- python - 有没有办法在不声明的情况下调用变量
- python - 应用 .nsmallest(2) 后计算 Pandas 中 Groupby 对象的平均值