- Home /
Script behaving too early
My script is behaving too early when clicked. Here's my code:
var targetScript : ChangeSprite;
var AcceptInput : boolean = true;
private static var score : int = 0;
var guiScore : GUIText;
function Start ()
{
guiScore.text = "Score: 0";
}
function OnMouseDown () {
if(AcceptInput)
{
AcceptInput = false;
}
targetScript = GameObject.Find("Shape").GetComponent(ChangeSprite);
GameObject.Find("Shape").GetComponent(ChangeSprite).enabled = true;
Debug.Log("Clicked");
if(targetScript.spriteRenderer.sprite == targetScript.diamond) {
score += 1;
guiScore.text = "Score: " + score;
}
else{
Debug.Log("Wrong Answer!");
}
}
function OnMouseUp () {
AcceptInput = true;
GameObject.Find("Shape").GetComponent(ChangeSprite).enabled = false;
}
It changes the sprite too early. When I press the button it would add the score before it even displayed the sprite. Any ideas? Any help would be much appreciated. Thanks
What is the behavior you want to have?
Right now you are adding the score and displaying a sprite in the same method call so the next time the screen is rendered after $$anonymous$$ouse Down happens, the increased score will be shown with the sprite.
If you want to have e.g. a one second delay you have to specifically program it because the screen doesn't get redrawn in between the lines of code in the On$$anonymous$$ouseDown function.
why have you used the AcceptInput
bool?
you set it to true
in On$$anonymous$$ouseUp()
but On$$anonymous$$ouseDown()
just does this
if(AcceptInput)
{
AcceptInput = false;
}
which is the same as
AcceptInput = false;
AND you don't do anything depending on it's value.
did you intend for the other 'logic' to run only if it's true
?
also, perfor$$anonymous$$g GetComponent() is a relatively slow operation to perform many times. consider moving this line to Awake()/Start()
targetScript = GameObject.Find("Shape").GetComponent(ChangeSprite);
and change other uses of
GameObject.Find("Shape").GetComponent(ChangeSprite)
to
targetScript
I used the accept input boolean so it doesn't flash through sprites if i hold it. @gjf
how can you add a delay to a behavier? @Nose$$anonymous$$ills
the code you have is the same as setting it to false
every time. are you using it somewhere else?
Answer by KellyThomas · Aug 03, 2014 at 09:43 AM
If you are using AcceptInput
to ensure that the code in OnMouseDown()
is not called repeatedly I suggest using a lock like this:
function OnMouseDown () {
if(!AcceptInput){
return;
}
AcceptInput = false;
// ...
}
function OnMouseUp () {
AcceptInput = true;
// ...
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to restrict a button for a second 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to save the best score 1 Answer
Multiple choice game not working!?! 1 Answer