Okay so I’m trying to build a Pong clone. This is my first solo project outside of tutorials so it goes without saying that I am very inexperienced. Everything was going well (or so I thought) until I hit this point.
The title explains my initial problem but now I’m starting to doubt every decision I have made with the logic and flow of my code. There are 3 classes that are working together which I’m going to open up to you guys for a good old critique if you willing and up for the task.
I’m getting the following error when player2’s score reaches 2:
NullReferenceException: Object reference not set to an instance of an object
GameManagement.UpdateScore2 () (at Assets/Scripts/GameManagement.cs:37)
Ball.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/Ball.cs:27)
public class Ball : MonoBehaviour
{
[SerializeField] float xPush = -10f, yPush = 0f;
Rigidbody2D myRididbody;
GameManagement myGame;
// Start is called before the first frame update
void Start()
{
myGame = FindObjectOfType<GameManagement>();
myRididbody = GetComponent<Rigidbody2D>();
myRididbody.velocity = new Vector2(xPush, yPush);
}
private void OnCollisionEnter2D(Collision2D collision)
{
myRididbody.velocity = new Vector2(myRididbody.velocity.x , Random.Range(-4, 4));
// Debug.Log(myRididbody.velocity);
if (collision.gameObject.tag == "ScoreWallLeft")
{
myGame.UpdateScore2();
Debug.Log("Collision with tag detected");
}
if (collision.gameObject.tag == "ScoreWallRight")
{
myGame.UpdateScore1();
Debug.Log("Collision with tag detected");
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
public class GameManagement : MonoBehaviour
{
[SerializeField] TextMeshProUGUI Player1ScoreText;
[SerializeField] TextMeshProUGUI Player2ScoreText;
Victory victor;
int player1Score = 0;
int player2Score = 0;
public void OnButtonPressed(int sceneID)
{
SceneManager.LoadScene(sceneID);
}
public void UpdateScore1() // udates score for player 1
{
player1Score++;
Debug.Log(player1Score);
Player1ScoreText.text = player1Score.ToString();
}
public void UpdateScore2() // updates score for player 2
{
player2Score++;
Player2ScoreText.text = player2Score.ToString();
if (player2Score >= 2)
{
victor.SetWinner("Player 2");
EndRound();
}
}
public void EndRound()
{
SceneManager.LoadScene("Game Over");
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Victory : MonoBehaviour
{
//TextMeshProUGUI VictoryText;
string winner = "";
private void Awake()
{
int scriptCount = FindObjectsOfType<Victory>().Length;
if (scriptCount > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
DisplayWinner();
}
}
public void SetWinner(string player)
{
winner = player;
}
public void DisplayWinner()
{
gameObject.GetComponent<TextMeshProUGUI>().text = winner;
}
}