Why is my Experience Script not working?

So i have been working on improving my scripting for a while and i am trying to implement an experience system. Just a basic, kill something and it gives experience. Below i have put my ExperienceScript and EnemyHealth script.

ExperienceScript

    var currentExperience : int;
    var maxExperience : int = 100;
    
    function GiveExperience ()
    {
    	var experienceGain = EnemyHealth.experienceGain;
    	currentExperience += experienceGain;
    	Debug.Log("You Gained Experience");
    	if(currentExperience >= maxExperience)
    	{
    		Debug.Log("LEVEL UP!");
    	}
    }

EnemyHealth

var Health = 100;
static var experienceGain : float = 50;

function Update ()
{
	if(Health <= 0)
	{
		Dead();
	}
}

function ApplyDamage (Damage : int)		
{
	Health -= Damage;
}

function Dead ()
{
	Destroy(gameObject);
	Experience();
}

function Experience ()
{
	var experienceScript : ExperienceScript;
	experienceScript.GiveExperience();
}

EDIT: Sorry about that, i am getting this error when the enemy gets to 0 health, instead of dieing i get this

NullReferenceException: Object reference not set to an instance of an object
EnemyHealth.Experience () (at Assets/Scripts/EnemyHealth.js:28)
EnemyHealth.Dead () (at Assets/Scripts/EnemyHealth.js:21)
EnemyHealth.Update () (at Assets/Scripts/EnemyHealth.js:9)

You’re creating a new experienceScript each time you kill a monster. I suggest you making the experienceScript static :slight_smile:

you are trying to execute a method of a class that cease to exist before executing

Destroy(gameObject); << Destroys to the class and anything next this point would not be executed
Experience(); << Method is unreached code, since gameobject with this script is destroyed

also as NickP_2 said, you are instantiating a new experienceScript Object, but you could make it static OR calling the script already in the scene

  1. Find the gameobject who has the experienceScript ie GameObject.Find(“WhoeverHasExpScript”)
  2. Get the script component from it and use it GameObject.Find(“WhoeverHasExpScript”).GetComponent().GiveExperience();

this code is in C#, but JS has something similar