- Home /
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 should add some more information. What is not working? How do you expect it to work? Is it not logging? Does it output errors? What have you tried to get it to work?
Only saying that things do not work and giving us some code is generally a bad practice, the more information we have the easier and more likely it is that anyone can and will give you a proper answer. =)
Answer by poncho · Feb 05, 2014 at 09:22 PM
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
Find the gameobject who has the experienceScript ie GameObject.Find("WhoeverHasExpScript")
Get the script component from it and use it GameObject.Find("WhoeverHasExpScript").GetComponent().GiveExperience();
this code is in C#, but JS has something similar
Thank you so much, i added in the piece of code you said into the dead function and it works now. Again thank you so much
Answer by NickP_2 · Feb 05, 2014 at 03:14 PM
You're creating a new experienceScript
each time you kill a monster. I suggest you making the experienceScript
static :)
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
What is wrong with this script? 2 Answers
BCE0044 expecting ), found 'script' and BCE0043 unexpected token ) 2 Answers
Amnesia style 1 Answer