- Home /
Score system
I'm programming a simple 2d game for android where you have to kill (destuir) objects that appear on the screen by touching them with your finger, then in my code the score is not working properly because the score increases as had destroyed all the objects in the game, and should be destroyed only assume as one
this is my code
using UnityEngine;
using System.Collections;
public class AddPoints : MonoBehaviour
{
void Update ()
{
if (Input.anyKeyDown)
{
PointScore.pointScore += 1f;
}
}
void OnMouseDown(){
Destroy (this.gameObject);
}
public float lifetime = 1.0f;
void Awake ()
{
Destroy(this, lifetime);
}
}
and
using UnityEngine;
using System.Collections;
public class PointScore : MonoBehaviour
{
public static float pointScore = 0;
void OnGUI ()
{
GUI.Label (new Rect (10, 10, 100, 20), "Score: " + pointScore);
}
}
if you can help I would be very grateful
Format this properly, make sure the code you are supplying is relevant to the problem description; make it clear what these scripts are attached to; does On$$anonymous$$ouseDown work for Android?
Answer by Pyrian · Apr 16, 2014 at 02:17 AM
You shouldn't be using "Input.anyKeyDown" to update your score. That will return true for EVERY object testing it, for EVERY keystroke or click; thus, your score updates by the number of scoreable objects with every click.
Remove that code, and just put your "PointScore.pointScore += 1f;" in the same OnMouseDown function with your Destroy, and you should be fine.
Thanks for the answer, but still have a problem because now when I click the object does not increase score or destroys the object
this is the code you recomend
using UnityEngine;
using System.Collections;
public class AddPoints : $$anonymous$$onoBehaviour
{
void On$$anonymous$$ouseDown ()
{
PointScore.pointScore += 1f;
Destroy (this.gameObject);
}
public float lifetime = 1.0f;
void Awake ()
{
Destroy(this, lifetime);
}
}
if you have another idea to resolve the problem I would be very grateful
I didn't realize they weren't being destroyed, either. There are a number of things that can prevent On$$anonymous$$ouseDown from being called, but let's start with the obvious: Does the same GameObject that AddPoints is attached to have an appropriate Collider component that covers its area? Without a collider, On$$anonymous$$ouseDown will never get called.
Also, it might not get called if it's under another object or on the IgnoreRayCast Layer.
I have the object with collider and rigidbody 2d and is the default layer