I'm having a problem changing the scoring values using TextMeshPro in a canvas from a script within the canvas. I'm getting a NullPointerException error because i feel that i am not referencing the score text files correctly but im not sure how to do it correclty. Error :
NullReferenceException: Object reference not set to an instance of an object Score.PlayerOneScored () (at Assets/Scripts/Score.cs:20)
Code :
public class Score : MonoBehaviour
{
static int scoreValue1 = 0;
static int scoreValue2 = 0;
private TMP_Text score1;
private TMP_Text score2;
public void PlayerOneScored() {
Debug.Log("Player One Scored");
scoreValue1++;
TMP_Text score1 = GetComponent<TextMeshProUGUI>();
Debug.Log("P1 Score: " + scoreValue1);
score1.text = "Score: " + scoreValue1;
}
public void PlayerTwoScored()
{
Debug.Log("Player Two Scored");
scoreValue2++;
TMP_Text score2 = GetComponent<TMP_Text>();
Debug.Log("P2 Score: " + scoreValue2);
score2.text = "Score: " + scoreValue2;
}
}
Line 20 is
score1.text = "Score: " + scoreValue1;
Picture of the Hierarchy : ScoreCanvas
Update Have it working now! This was my class in the end
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Score : MonoBehaviour
{
static int scoreValue1 = 0;
static int scoreValue2 = 0;
public TextMeshProUGUI score1;
public TextMeshProUGUI score2;
void Awake()
{
score1.text = "Score: " + scoreValue1;
score2.text = "Score: " + scoreValue2;
}
public void PlayerOneScored() {
if (scoreValue1 < 10) {
scoreValue1++;
Debug.Log("Player One Scored");
Debug.Log("P1 Score: " + scoreValue1);
score1.text = "Score: " + scoreValue1;
}
else { }
}
public void PlayerTwoScored()
{
if (scoreValue2 < 10)
{
scoreValue2++;
Debug.Log("Player Two Scored");
Debug.Log("P2 Score: " + scoreValue2);
score2.text = "Score: " + scoreValue2;
}
else { }
}
}