Score not adding up, enemy not dying and giving null reference error

Hello,
After adding the below line of code in enemy script, enemy is not dying any more. And score also not adding up

    FindObjectOfType<GameSession>().AddToScore(scoreValue);

And giving below errors as well.

NullReferenceException: Object reference not set to an instance of an object
Enemy.Die () (at Assets/Scripts/Enemy.cs:75)
Enemy.ProcessHit (DamageDealer damageDealer) (at Assets/Scripts/Enemy.cs:69)
Enemy.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Enemy.cs:60)

I have followed exactly as shown in the lecture, no changes. Only I am using Unity 2019.3.7f1 version.

Below are the scripts for reference.

  1. ScoreDisplay.cs

using UnityEngine;
using UnityEngine.UI;

public class ScoreDisplay : MonoBehaviour
{
Text scoreText;
GameSession gameSession;

void Start()
{
    scoreText = GetComponent<Text>();
    gameSession = FindObjectOfType<GameSession>();
}

void Update()
{
    scoreText.text = gameSession.GetScore().ToString();
}

}

  1. GameSession.cs

using UnityEngine;

public class GameSession : MonoBehaviour
{
int score = 0;
int health = 0;

private void Awake()
{
    SetUpSingleton();
}

private void SetUpSingleton()
{
    int numberGameSessions = FindObjectsOfType<GameObject>().Length;
    if (numberGameSessions > 1)
    {
        Destroy(gameObject);
    }
    else
    {
        DontDestroyOnLoad(gameObject);
    }
}

public int GetScore()
{
    return score;
}

public void AddToScore(int scoreValue)
{
    score += scoreValue;
}

public void ResetGame()
{
    Destroy(gameObject);
}

}

  1. Enemy.cs

using UnityEngine;

public class Enemy : MonoBehaviour
{
[Header(“Enemy Stats”)]
[SerializeField] float health = 100;
[SerializeField] int scoreValue = 150;

[Header("Shooting")]
[SerializeField] float shotCounter;
[SerializeField] float minTimeBetweenShots = 0.3f;
[SerializeField] float maxTimeBetweenShots = 3f;
[SerializeField] GameObject projectile;
[SerializeField] float projectileSpeed = 10f;

[Header("Sound Effect")]
[SerializeField] GameObject deathVFX;
[SerializeField] float durationOfExplosion = 1f;
[SerializeField] AudioClip deathSound;    
[SerializeField] [Range(0, 1)] float deathSoundVolume = 0.7f;
[SerializeField] AudioClip shootSound;
[SerializeField] [Range(0, 1)] float shootSoundVolume = 0.25f;

void Start()
{
    shotCounter = Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
}

void Update()
{
    CountDownAndShoot();
}

private void CountDownAndShoot()
{
    shotCounter -= Time.deltaTime;
    if (shotCounter <= 0f)
    {
        Fire();
        shotCounter = Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
    }
}

private void Fire()
{
    GameObject laser = Instantiate(
                projectile,
                transform.position,
                Quaternion.identity) as GameObject;
    laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -projectileSpeed);
    AudioSource.PlayClipAtPoint(shootSound, Camera.main.transform.position, shootSoundVolume);
}
private void OnTriggerEnter2D(Collider2D other)
{
    DamageDealer damageDealer = other.gameObject.GetComponent<DamageDealer>();
    if (!damageDealer) { return; }
    ProcessHit(damageDealer);
}

private void ProcessHit(DamageDealer damageDealer)
{
    health -= damageDealer.GetDamage();
    damageDealer.Hit();
    if (health <= 0)
    {
        Die();
    }
}

private void Die()
{
    FindObjectOfType<GameSession>().AddToScore(scoreValue);
    Destroy(gameObject);
    GameObject explosion = Instantiate(deathVFX, transform.position, transform.rotation);
    Destroy(explosion, durationOfExplosion);
    AudioSource.PlayClipAtPoint(deathSound, Camera.main.transform.position, deathSoundVolume);
}

}

Hi,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.


See also:

Hi,

I am not able to figure out, this null reference exception I saw in other threads but didn’t understood. Sorry
Kindly explain in detail.

To which line in your code does the error message refer? To this one?

FindObjectOfType<GameSession>().AddToScore(scoreValue);

If so, check if there is a GameSession object in your scene.

Hi,

Yes I have game session object in the scene. Below are the images for reference :-

Below is the image, this is happening in the game.

And error message is pointing to below lines also :-

         Die();

        ProcessHit(damageDealer);

In the bottom screenshot, is there the Game Session game object in the Hierarchy?

Is GameSession a “singelton”/persistent object?

Try this =D

  1. ScoreDisplay.cs

using UnityEngine;
using UnityEngine.UI;

public class ScoreDisplay : MonoBehaviour
{
Text scoreText;

void Start()
{
    scoreText = GetComponent<Text>();
}

void Update()
{
    if(!scoreText) {Debug.Log("noScoreText"); return;}
    if(GameSession.INSTANCE == NULL) Debug.Log("NoGameSession");
    scoreText.text = GameSession.INSTANCE?.GetScore().ToString();
}


}
  1. Enemy.cs

using UnityEngine;

public class Enemy : MonoBehaviour
{
[Header(“Enemy Stats”)]
[SerializeField] float health = 100;
[SerializeField] int scoreValue = 150;

[Header("Shooting")]
[SerializeField] float shotCounter;
[SerializeField] float minTimeBetweenShots = 0.3f;
[SerializeField] float maxTimeBetweenShots = 3f;
[SerializeField] GameObject projectile;
[SerializeField] float projectileSpeed = 10f;

[Header("Sound Effect")]
[SerializeField] GameObject deathVFX;
[SerializeField] float durationOfExplosion = 1f;
[SerializeField] AudioClip deathSound;    
[SerializeField] [Range(0, 1)] float deathSoundVolume = 0.7f;
[SerializeField] AudioClip shootSound;
[SerializeField] [Range(0, 1)] float shootSoundVolume = 0.25f;

void Start()
{
    shotCounter = Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
}

void Update()
{
    CountDownAndShoot();
}

private void CountDownAndShoot()
{
    shotCounter -= Time.deltaTime;
    if (shotCounter <= 0f)
    {
        Fire();
        shotCounter = Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
    }
}

private void Fire()
{
    GameObject laser = Instantiate(
                projectile,
                transform.position,
                Quaternion.identity) as GameObject;
    laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -projectileSpeed);
    AudioSource.PlayClipAtPoint(shootSound, Camera.main.transform.position, shootSoundVolume);
}
private void OnTriggerEnter2D(Collider2D other)
{
    DamageDealer damageDealer = other.gameObject.GetComponent<DamageDealer>();
    if (!damageDealer) { return; }
    ProcessHit(damageDealer);
}

private void ProcessHit(DamageDealer damageDealer)
{
    health -= damageDealer.GetDamage();
    damageDealer.Hit();
    if (health <= 0)
    {
        Die();
    }
}

private void Die()
{
    GameSession.INSTANCE?.AddToScore(scoreValue);
    Destroy(gameObject);
    GameObject explosion = Instantiate(deathVFX, transform.position, transform.rotation);
    Destroy(explosion, durationOfExplosion);
    AudioSource.PlayClipAtPoint(deathSound, Camera.main.transform.position, deathSoundVolume);
}

}
1 Like

Hi,

Thank you very very much for your help. Now the score is adding up and enemy is also destroying.
Now

  1. Console is showing below msg when player is dying and when I click “play again” from game over scene.

       NoGameSession
       UnityEngine.Debug:Log(Object)
       ScoreDisplay:Update() (at Assets/Scripts/ScoreDisplay.cs:25) 
    

What does this mean :slightly_frowning_face:

error image

  1. when I click on "start " button from start menu scene getting one error for level.cs script.

below is the level.cs script which is highlighting when selecting the error

public void LoadGame()
{
SceneManager.LoadScene(“Game”);
FindObjectOfType().ResetGame();
}

error image

Till this point I have’t found any issues in game play. Does the above Null reference exception error needs attention ??

Actually I have no experience in programming and all. This is the first course I am learning so I am having little hard time in small-small things.
Thanks a lot in advance.

Hi Nina,

Yes Game session game object is in the hierarchy and it is singleton.

I didn’t check @111100’s code. They know probably best what they suggested.

If you were not able to implement their code, modify your GameSession.cs according to this:

    if (numberGameSessions > 1)
    {
        gameObject.SetActive(false);
        Destroy(gameObject);
    }

The first message is not an error its Debug.Log(); you can ignore it.

The second one is an error. If you copy paste your level script maybe i help you. I finished this part long ago and really dont remember.

Also if your code have somewhere FindObjectOfType<GameSession>(). replace with GameSession.INSTANCE. (or GameSession.INSTANCE?. if you call method to check if its not null)

In GameSession script i made public static variable INSTANCE of type GameSession.
When variable is public static you can call it directly from class like this GameSession.INSTANCE and not searching it in hierarchy. But first it needs to be assigned to not get null references.

1 Like

Hi,

Applying this as you told solved the error. I have covered all this game lectures and everything is working fine. Thank you very much. :pray:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms