Reputation: 199
My problem is that the code will only work the first item (Star Tablet) that the player touches. After that, the number will remain 1. I suspect that my Destroy() function erases the script and the count must be forgotten? However, I don't know of any alternative measures to take. If I'm wrong about that, please inform me of what is going wrong and what steps I'd need to fix it. Here is my entire script:
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;
}
}
Upvotes: 0
Views: 283
Reputation: 15941
Each copy has this:
private int starTabCollected;
This means that each one you pick up is always the first one.
Upvotes: 2