- Home /
There is already a local variable error. Thrown when updating a variable 2 diffrent times in a script
I have coded a script that keeps track of a money balance when buying various things. I have defined the money
variable at the beginning of the script with public var money : float = 1000;
with 1000 being the starting balance. Updating the variable later in the script with var money = money - fieldCost
works perfectly fine for subtracting fieldCost
from money
, but when using that and, later in the script var money = money - gardenCost
to subtract gardenCost
from money
, compiler throws: NullReferenceException: Object reference not set to an instance of an object
on the line of the var money = money - gardenCost
. (yes, its a farm game) I might be just noobing this, as I am one, but it is the only thing preventing my game from running and I just can't figure it out!
I haven't yet written the code that sets the boughtField
and boughtGarden
to true, should that matter.
Code:
#pragma strict
public var money : float = 1000;
public internal var boughtField : boolean = false;
public var fieldCost : float = 150;
public internal var boughtGarden : boolean = false;
public var gardenCost : float = 100;
function Start () {
}
function Update () {
//print balance to console
// Debug.Log("CurrentBalance is " + money);
//run buyplot function
BuyPlot ();
}
// processes when player has bought something
function BuyPlot () {
//has the player bought a field?
if (boughtField == true) {
//do they have enough money to buy a field
if (money >= fieldCost) {
//enough money, purchase field
var money = money - fieldCost;
}
//not enough money, sends message
else {
Debug.Log("Not enough money to purchase Field!");
}
}
//has the player bought a garden?
if (boughtGarden == true) {
//do they have enough money
if (money >= gardenCost) {
//enough money, purchase garden
var money = money - gardenCost;
}
//not enough money, send message
else {
Debug.Log("Not enough Money to buy Garden!");
}
}
}
Answer by getyour411 · Apr 22, 2014 at 11:48 PM
Remove "var" from the inner references
Example
var money = money - fieldCost;
to this
money = money - fieldCost;
Your answer
Follow this Question
Related Questions
How to fix error BCE0005: Unknown identifier 1 Answer
Converting from js to c# 1 Answer
What is wrong in this script? 1 Answer
In the editor, the script works fine, but in the build, no! 0 Answers
the associated script cannot be loaded 0 Answers