Please Help. How to add score on collision mobile?
Hello everyone. I am creating a 2d Mobile, touchscreen game for unity. I would like to have a UI score increase every time I touch the object. When I touch the specified object there is a collision but I want to enable a score for when these objects collide when I touch them. I will select the best answer.
Answer by Ben-Stoneman · Aug 24, 2015 at 10:13 AM
@putback This will work as a basis for what you want:
using UnityEngine;
using System.Collections;
using UnityEngine.UI; //Required when using UI elements in the script.
public class ExampleScript : MonoBehaviour {
public int currentScore;
public Text displayScore;
// Invoked on collision
void OnCollisionEnter2D (Collision2D coll)
{
if (coll.gameObject.tag == "Player")
{
//Add 20 points each time the player collides
// with the object this script is attached to
currentScore += 20;
}
}
// Update is called once per frame
void Update ()
{
displayScore.text = currentScore.ToString();
}
}
Answer by putback · Aug 27, 2015 at 07:56 AM
@Ben Stoneman . I need help, for some reason the score count is staying at 0 and I keep getting the error: Null Reference Exception: Object reference not set to an instance of an object.
on lithis line: displayScore.text = currentScore.ToString();
you haven't assigned the text that you want to display to the inspector yet
you should assign by drag and drop the name of the text you want to display in hierarchy into the empty slot that has the name "displayScore" in the Inspector
Your answer
![](https://koobas.hobune.stream/wayback/20220612001208im_/https://answers.unity.com/themes/thub/images/avi.jpg)