Hello,
I am pretty new to C# and I’m trying to make a game in unity. The game is a clone of pong. I’ve been doing very well until now, but when I try to change the score label text when it hits the goal, it gives me an error. Here is my goal script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RightGoal : MonoBehaviour
{
private int leftScore = 0;
public GameObject canvas;
void OnTriggerEnter2D(Collider2D collider)
{
leftScore += 1;
GameObject leftScoreGameobject = canvas.transform.Find("LeftScore").gameObject;
Text leftScoreText = leftScoreGameobject.GetComponent<Text>();
string leftScoreStr = leftScore.ToString();
Debug.Log(leftScoreStr);
leftScoreText.text = "1";
collider.transform.position = new Vector2(0f, 0f);
collider.GetComponent<Ball>().Direction();
}
}
And here is a screenshot of the whole unity editor(in case it helps):
The exact error is:
NullReferenceException: Object reference not set to an instance of an object
RightGoal.OnTriggerEnter2D (UnityEngine.Collider2D collider) (at Assets/Scripts/Goals/RightGoal.cs:17)
I searched many forums, and they said that it may be something missing, but i don’t see anything that is not where it is supposed to be.
I hope someone can help me!
P.S: RightGoal.cs is the script above the image.
P.S. 2: I am happy to give more info if you need