Coin Counter showing total coins per level help
I'm making a roll-a-ball game, and I want to have a counter on screen for the amount of coins collected, and the total amount of coins on screen. I also want to spawn a game object once all coins are collected.
Here is my code on my Player:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
public Text countText;
public Text winText;
public AudioClip CollectSound;
private Rigidbody rb;
private int count;
void Start ()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText ();
winText.text = "";
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other)
{
AudioSource.PlayClipAtPoint(CollectSound, transform.position);
if (other.gameObject.CompareTag ( "Coin"))
{
other.gameObject.SetActive (false);
count = count + 1;
SetCountText ();
}
}
void SetCountText ()
{
GameObject[] Coin = GameObject.FindGameObjectsWithTag("Coin");
int total = Coin.Length;
countText.text = count.ToString () + "/" + total ;
if (count >= total )
{
winText.text = "Portal Open";
}
}
}
My problem is that after I collect a coin, it seems to be removed from the game. The counter goes from 0/3 to 1/2 to 2/1 to 3/0.
Since my code check to see if you have >= The total coins per level, winning condition is met early. I don't know how to fix this.
Can't you just compare (count >= 3) ins$$anonymous$$d of Coin.Length?
to spawn (instantiate):
GameObject ob = GameObject.Find("nameOfYourGameObject"); GameObject g = Instantiate(ob); //optional setters: g.transform.position = new Vector3(0,0,0); //where ever you want it. g.transform.SetParent(GameObject.Find(p).transform); //p is whatever you want to be its parent
or if you are not spawning but merely activating an inactive object. ob.setActive(true);