- Home /
I am trying to get the score to reset back to zero in an asteroids like game I am programming.
So I got the score to increase every time I destroy an enemy. But I can't seem to get the score to reset back to zero when all enemies on screen have been destroyed. Someone help me out please. Here is my code.
using UnityEngine; using System.Collections;
public class Rock : MonoBehaviour { public int movementSpeed = 2; GameManager gm; public int score; public Vector3 sizepos;
// Use this for initialization
void Start ()
{
sizepos = this.transform.localScale;
transform.Rotate (0.0f, 0.0f, Random.Range (0.0f, 360.0f));
gm = GameObject.Find ("GameManager").GetComponent<GameManager> ();
}
// Update is called once per frame
void Update ()
{
if (this.gameObject == null) {
gm.score = 0;
}
//rigidbody2D.AddForce (transform.up * movementSpeed * Time.deltaTime);
transform.Translate (Vector3.up * Time.deltaTime * movementSpeed);
}
void OnTriggerEnter2D (Collider2D other)
{
if (!other.gameObject.CompareTag ("Rock")) {
if (this.transform.localScale.x > 0.25f) {
for (int i = 0; i < 2; i++) {
gm.Rock (this.transform.position, this.transform.localScale.x / 2.0f);
}
}
Destroy (this.gameObject);
if (this.transform.localScale.x >= 0.25f && this.transform.localScale.x <= 0.25f) {
gm.score += 100;
Debug.Log ("score:" + score);
}
if (this.transform.localScale.x >= 0.5f && this.transform.localScale.x <= 0.5f) {
gm.score += 50;
Debug.Log ("score:" + score);
}
if (this.transform.localScale.x >= 1f && this.transform.localScale.x <= 1f) {
gm.score += 20;
}
}
}
}
Answer by Kiwasi · Jun 09, 2014 at 07:51 AM
By definition this.gameObject will never be null. Hence score will never be reset.
To get a score that resets try the following
// On the GameManager Component
public int Count;
Update () {
// Do whatever
if (Count<=0){
Score = 0;
}
// Do some other stuff
}
// On the asteroid
Start(){
// The other start stuff
gm.Count++;
}
void OnTriggerEnter2D (Collider2D other){
// Do the other stuff
gm.Count--;
destroy(gameObject);
// Do not do anything here, it will not run
}
Incidentally the this is implicit in MonoBehavior for gameObject and transform.
Also nothing will run after line 34, destroyed GameObjects stop running all code as soon as destroy is called
Your answer
Follow this Question
Related Questions
Problem with playmaker gui and "Get mouse button down" action. 1 Answer
Particle System On Key Press 2 Answers
Enemy not moving towards Player 0 Answers
Distribute terrain in zones 3 Answers
Start Coroutine after other has finished 4 Answers