首页 > 解决方案 > 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;
    }    
}

标签: c#user-interfaceunity3d

解决方案


您在场景中有三个脚本副本

每个副本都有这个:

private int starTabCollected;

这意味着你拿起的每一个总是第一个。


推荐阅读