errors
NullReferenceException: Object reference not set to an instance of an object
GameSession.AddToScore (System.Int32 pointsToAdd) (at Assets/Scripts/GameSession.cs:53)
BeerPickup.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/BeerPickup.cs:14)
Brain hurts, lol
Worked fine util I added the score script now pickups don’t work again and I get null ref errors. So confused. I see what the errors are saying and where I made the mistakes but, I still don’t understand what I did wrong.
Scripts
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BeerPickup : MonoBehaviour
{
[SerializeField] AudioClip beerPickupSFX;
[SerializeField] int pointsForBeerPickup = 1;
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
FindObjectOfType<GameSession>().AddToScore(pointsForBeerPickup);
AudioSource.PlayClipAtPoint(beerPickupSFX, Camera.main.transform.position);
Destroy(gameObject);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
public class GameSession : MonoBehaviour
{
[SerializeField] int score = 0;
[SerializeField] int playerLives = 3;
[SerializeField] TextMeshProUGUI livesText;
[SerializeField] TextMeshProUGUI scoreText;
void Awake()
{
int numGameSessions = FindObjectsOfType<GameSession>().Length;
if (numGameSessions > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
livesText.text = playerLives.ToString();
scoreText.text = score.ToString();
}
public void ProcessPlayerDeath()
{
if (playerLives > 1)
{
TakeLife();
}
else
{
ResetGameSession();
}
}
public void AddToScore(int pointsToAdd)
{
score += pointsToAdd;
scoreText.text = score.ToString();
}
void TakeLife()
{
playerLives--;
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentSceneIndex);
livesText.text = playerLives.ToString();
}
void ResetGameSession()
{
SceneManager.LoadScene(0);
Destroy(gameObject);
}
}