- Home /
Collecting 2 items at a time by mistake.
I have a very simple game where the goal is to collect 15 stars. Everything works fine except that some of the stars count for 2 points instead of 1. I tried deleting the stars that get counted twice, but it changes every time. If I play it, a star will be counted once, then the next time I play it, maybe that star gets counted as 2 points. Its very random and I dont know why its happening. I only want each star to be worth 1 point.
using UnityEngine;
using System.Collections;
public class Collect : MonoBehaviour
{
public GUIText countText;
public GUIText winText;
private int count;
void Start ()
{
count = 0;
SetCountText ();
winText.text = "";
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Star")
{
other.gameObject.SetActive(false);
count = count + 1;
SetCountText ();
}
}
void SetCountText ()
{
countText.text = "Stars: " + count.ToString();
if(count >= 15)
{
winText.text = "YOU WIN!";
}
}
}
You are given the option to edit your questions, or at the very least, to comment. Do not post updated information as an answer, if only because it makes it look like your question has already been answered, so people are less likely to read it.
Sorry, I haven't used the answers very much, I just wanted some help. The code is there now. Anyone have any advice?
It has to be something other than your code...At least imo. I don't see anything that would be causing it with the code you gave :|
Thats what I was thinking it might be, but I couldnt figure out what else could be causing it Ive also noticed that some of them count for 2 points or 3 points or even bigger numbers like 23 points. It just seems so random and I cant figure out why they arent couting by 1 each time.
Answer by BladeWarrior · May 12, 2020 at 11:16 AM
A friend helped me fix this by taking out the "count + 1" and have it calucalate by getting the total and subtracting the collect action which gives you how many was collected. Code below is working for me.
public Text CountText;
private int total;
private int nextScene;
// Use this for initialization
void Start()
{
total = GameObject.FindGameObjectsWithTag("collect").Length;
UpdateCount(total);
nextScene = SceneManager.GetActiveScene().buildIndex + 1;
}
void OnTriggerEnter(Collider ThingCollidedWith)
{
if (ThingCollidedWith.gameObject.CompareTag("collect"))
{
Destroy(ThingCollidedWith.gameObject);
}
}
void Update()
{
var count = GameObject.FindGameObjectsWithTag("collect").Length;
UpdateCount(count);
if (count == 0)
{
SceneManager.LoadScene(nextScene);
}
}
void UpdateCount(int count)
{
CountText.text = "You've collected " + (total - count) + " / " + total;
}
}