- Home /
Scripting problem, with values and input.getbutton
Hey all, I've been tinkering around a tiny scavenging system for a game i'm working on - at this moment. All it i supposed to do is add a certain amount of food/scrap to a value in my gameplayglobals script if i press the scavenge button while inside the triggerzone attached to a crate - and then destroy the crate. It works, i get (in this case food) added to my globals - BUT i get it added about 22 times, instead of just adding one "portion" of 1-4 food.
var IsFoodContainer : boolean = false;
var IsScrapContainer : boolean = false;
static var FoodAmount = Random.Range(1,4);
static var ScrapAmount = Random.Range(1,5);
function OnTriggerStay (other : Collider) {
// IF player scavenges while in zone
if (Input.GetButtonDown ("Scavenge")&& IsFoodContainer == true){
AddFood();
}
// If player rolls 2, roll amount, and goto addscrap,
if (Input.GetButtonDown ("Scavenge") && IsScrapContainer == true){
AddScrap();
}
}
function AddFood(){
GameplayGlobals.foodAmount += FoodAmount;
Debug.Log("ADDED FOOD"+FoodAmount);
Destroy(gameObject);
}
//////////////////////////////////////////////////////////////////////////////////////
function AddScrap(){
GameplayGlobals.scrapAmount += ScrapAmount;
Debug.Log("Added SCRAP"+ScrapAmount);
Destroy(gameObject);
}
I really hope someone can help me here - i've tried all the different "Input.GetButton" variations (up/down) - tried rearranging the code in different matter. I've been staring blindly at the code for a while now. So I hope someone knows what to do:)
Thanks in advance. Lasse
Answer by aldonaletto · Oct 10, 2011 at 08:55 PM
You should read Input.GetButtonDown only inside Update: it will return true during all the update cycle. If you read in FixedUpdate, OnTriggerStay, OnGUI - routines that are called at different paces - you may have this bad effect. You must change your logic a little: set a boolean variable at OnTriggerEnter and reset it at OnTriggerExit, and check the variable inside Update:
var inTrigger = false;
function OnTriggerEnter(other: Collider){ if (other.tag == "Player) inTrigger = true; }
function OnTriggerExit(other: Collider){ if (other.tag == "Player) inTrigger = false; }
function Update(){ if (inTrigger && Input.GetButtonDown("Scavenge"){ if (IsFoodContainer){ AddFood(); } if (IsScrapContainer){ AddScrap(); } } } NOTE: If IsFoodContainer and IsScrapContainer are both true, the player will do both things, because Destroy will take effect only after the current Update cycle.
Thanks man, $$anonymous$$uch appreciated:D I guess you learn something new every day^^
Your answer
Follow this Question
Related Questions
Great unity X Y value (Space game) 0 Answers
Updating a Value in OnTriggerEnter and Returning That Value Immediately... 0 Answers
input button while in a trigger? 2 Answers
Input.getKeyDown alternative for XR Devices 1 Answer
Lightswitch help? 3 Answers