I know there is a lot of questions about unity scores etc however I am finding it hard to actually structure the code for my game and have reviewed loads of youtube tutorials and blogs posts. I was wondering if anyone could help me add a score so that every time I click one of my objects within my hidden object game it provides a score. I would really appreciate it. So far I have added a separate script called Score.cs..The code is as follows below. I then added it to my background image and included the script into each object my Score Text is within the canvas and currently does not count any objects that are being clicked.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour {
public Text scoreText;
public int gameObject;
private int score;
// Use this for initialization
void Start () {
score = 0;
UpdateScore ();
}
void OnMouseDown () {
score += gameObject;
UpdateScore ();
}
// Update is called once per frame
void UpdateScore () {
scoreText.text = "Score:\n" + score;
}
}
!***** EDIT (Score.cs) *****!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour {
public Text scoreText;
public int gameObject;
public int score;
// Use this for initialization
void Start () {
score = 0;
UpdateScore ();
}
void OnMouseDown () {
score += gameObject;
UpdateScore ();
}
// Update is called once per frame
void UpdateScore () {
scoreText.text = "Score:\n" + score;
}
}
!****** Clicker.cs ******!
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine;
public class Clicker : MonoBehaviour, IPointerClickHandler
{
Score score;
void Start()
{
addPhysics2DRaycaster();
//Get Score Script Instance
string scoreObject = "gameObject";
score = GameObject.Find(scoreObject).GetComponent<Score>();
}
void addPhysics2DRaycaster()
{
Physics2DRaycaster physicsRaycaster = GameObject.FindObjectOfType<Physics2DRaycaster>();
if (physicsRaycaster == null)
{
Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
}
}
public void OnPointerClick(PointerEventData eventData)
{
//Click detected. Increment score
score.score++;
Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
}
}