- Home /
Pass Function Values To Global Variables
Im trying to make it so when i call the function Mining(GV.IronOre, GV.IronOreExp); it will pass those variables to the function and increase those static variables. Right now i have about 10 if's checking if the name is = to something and thats annoying. Hopefully i can get some help with this. If you need more info just ask but tbh im not sure how else to explain it.
Note: GV is the name of the script where the global variables are stored.
function Start(){
Mining(GV.IronOre, GV.IronOreExp);
Mining(GV.CoalOre, GV.CoalOreExp);
}
function Mining(Item, Exp){
Item += 1;
Exp += 1;
}
Answer by Bunny83 · Apr 28, 2015 at 12:08 AM
You showed very little of your actual code. As @dota already said a ref parameter might be a solution but wouldn't be a nice one. Since you use UnityScript you can't even use it so you have to use something else.
First of all static variables have the big problem that you can't reference the instance that holds the variables since static things are instance-free. Furthermore it seems a bit strange to have seperate variables for different ore types hardcoded. You usually would use a class that has an "amount" variable and an "exp" variable. For each ore type you simply create an instance of that class. That way the interaction with an "ore" is always the same. You just need to pass the appropriate reference.
I don't really use UnityScript but it might look like this:
public class Ore extends System.Object
{
var name : String;
var amount : int;
var exp : int;
function Ore(aName : String)
{
name = aName;
}
function mining()
{
amount += 1;
exp += 1;
}
}
// inside your GV script
static var iron = new Ore("iron");
static var coal = new Ore("coal");
// in your other script
function Start(){
GV.iron.mining();
GV.coal.mining();
// or
Mining(GV.iron);
}
function Mining(ore : Ore) {
ore.amount += 1:
ore.exp += 1
}
Just for simplicity i stayed with the static variables. I would recommend some kind of manager class instead but that would go too far for this answer.
Thanks. You really helped me out with what i was looking for. Was a little more complex than what i wanted and needed a little tweaks but i got it to work. Thank you very much :D
Your answer
Follow this Question
Related Questions
Animation Event don't show C# methods 1 Answer
run function once per frame 2 Answers
Auto generated script with more functions? 0 Answers