- Home /
NullPointerException while changing a variable from one script in another
Hello, So I am trying to increment the score in one of my scrips when the person hits a coin. I think I may be linking my scripts wrong as I have been getting this error all night. I have tried a ton of different methods and have no idea. The tricky part being that the PlayerInfo script is on the player while the CoinOnCollision script is on the coin. any ideas?
PlayerInfo script
#pragma strict
var currentHealth : int = 10;
var maxHealth : int = 10;
public var currentScore : int = 0;
function RaiseScore(score : int) {
this.currentScore += score;
}
function Update () {
}
CoinOnCollision script
#pragma strict
var playerInfoScript : PlayerInfo;
function Start() {
playerInfoScript = GameObject.FindGameObjectWithTag("Player").GetComponent("playerInfoScript");
}
function OnTriggerEnter() {
playerInfoScript.currentScore += 10;
Destroy(gameObject);
}
Line 3 and line 6. The variable is of type PlayerInfo, the GetComponent method is passed a string "playerInfoScript". This is the error.
the error I'm getting is NullReferenceException: Object reference not set to an instance of an object CoinOnCollision.OnTriggerEnter () (at Assets/Standard Assets/Character Controllers/Sources/Scripts/CoinOnCollision.js:9)
Answer by fafase · Nov 29, 2013 at 07:33 AM
playerInfoScript or PlayerInfo?
The variable shows it should be a PlayerInfo but you are passing playerInfoScript
Also, you can remove the "" for the parameter it works better. Or add
GetComponent("ScriptName") as ScritpName;
doesn't the way I made it say a new variable called playerInfoScript of type PlayerInfo? or should it be the other way around. I seem to have using GetComponent no matter when I use it by I will try it that way. thanks :)
What is the name of your other script? That is what you need to use as type and as parameter for the GetComponent
the script that contains the variable I'm trying to change is called PlayerInfo and the script I am currently working in is CoinOnCollision
var script :PlayerInfo;
function Start(){
script = GameObject.FindGameObjectWithTag("Player").GetComponent(PlayerInfo);
}
function OnTriggerEnter() {
script.currentScore += 10;
Destroy(gameObject);
}
It works! thank you so much! I see what I was doing wrong now too :) your are a saint