Get XP on enemy death

Hello.

I was stucked with some weird problem for 2 days. Sometime ago I started to implement level system. I wrote it and wanted to write script for gaining experience on enemy death. I used event system to do this and subscribe to it, but I simply can’t trigger it in game upon enemy death.

Unity says: “Object reference not set to an instance of an object” at line 24 in BloodSucker script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class BloodSucker : MonoBehaviour {

    public int health;
    public GameObject effect;
    public GameObject corpse;

    public event EventHandler OnBloodSuckerKilled;

    public LevelSystem levelSystem;

    private void Update()
    {
        if (health <= 0) 
        {
            Instantiate(corpse, transform.position, Quaternion.identity);
            Instantiate(effect, transform.position, Quaternion.identity);
            Destroy(gameObject);

            OnBloodSuckerKilled.Invoke(levelSystem, EventArgs.Empty);
        }
    }

    public void TakeDamage(int damage) {
        health -= damage;
    }

    public void XP_OnBloodSuckerKilled(object sender, System.EventArgs e) {
        levelSystem.AddExperience(100);
        Debug.Log("This code working");
    }

    public void SetLevelSystem(LevelSystem levelSystem)
    {
        this.levelSystem = levelSystem;

        OnBloodSuckerKilled += XP_OnBloodSuckerKilled;
    }
}

You can say that I should make new LevelSystem, but I can’t, cause I have one more script that using my levelSystem, so I’ve created code that sends them original levelSystem in SetLevelSystem

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestingLvlSys : MonoBehaviour
{
 	public ExperienceBarUI experienceBarUI;
 	public BloodSucker bloodSucker;

 	LevelSystem levelSystem = new LevelSystem();

    public void Awake()
    {
    	experienceBarUI.SetLevelSystem(levelSystem);
    	bloodSucker.SetLevelSystem(levelSystem);
    }
}

So, I need to Invoke my XP_OnBloodSuckerKilled when enemy killed. How can I do that.
Thank you in advance for answers.

You will still need to assign level system in BloodSicker script. You created a new one in TestingLvlSys but if you want that to be the same one in BloodSicker then you have to assign it to that. To get XP_OnBloodSuckerKilled called when enemy dies you just need to call it in your if (health <= 0) check in your update.

I solved this problem!

I just send to TestingLvlSys death of the Bloodsucker and call function addExperience in it.