- Home /
Click Event Implementation Problem
I have this Clicked behaviour attached to a camera:
public class Clicked : MonoBehaviour {
//stores the object that received MouseDown for consumption by the iterator
private RaycastHit originalHit;
void Update () {
if (!Input.GetMouseButtonDown(0)){
//mouse not being clicked
return;
}
var camera = Camera.main;
if (!Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out originalHit, 100)){
print ("no object being clicked by mouse");
return;
}
var eventsBehaviour = originalHit.transform.GetComponent<SubscribedEvents>();
if(eventsBehaviour == null
|| !(eventsBehaviour is ISubscribeClicked)){
print ("no event subscriptions or does not subscribe to Clicked event");
return;
}
StartCoroutine(WaitOnUp(originalHit));
}
//waits on the mouse to be released on this object so that it only acts
//upon a mouse click that was completely on this object
IEnumerator WaitOnUp(RaycastHit hit){
while (!Input.GetMouseButtonUp(0)){
yield return 0;
}
if(!Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out hit, 100)){
print ("MouseUp not on an object");
}
else if(hit.GetHashCode () != originalHit.GetHashCode ()){
print("MouseUp on a different object");
}
else{
//object received MouseDown and then MouseUp, so fire its OnClicked event
print ("MouseUp on original object");
(originalHit.transform.GetComponent<SubscribedEvents>() as ISubscribeClicked).OnClicked();
}
}
}
However, if I quickly move the mouse to a different object after ensuring that MouseUp has occurred on the original object, I will see "MouseUp on a different object". Due to seeing this, it seems like calling
yield return 0
causes the program to not re-enter into the iterator every frame, as in it just skips some frames before re-entering. Is that true?
From what I think I remember reading, return 0 means come back next frame, and return null means come back in the same frame, which I don't want. However, in my desperation I tried it anyway and it didn't matter.
Answer by lumpydumpy · Jun 03, 2013 at 11:56 PM
I thought GetHashCode was implemented for RaycastHit. Apparently it wasn't, and thus my comparison at line 38 was failing whenever the mouse moved between MouseDown and MouseUp. GetHashCode is incorrect to use anyway, but it would have not worked in a different way. I used hit.transform.name instead, which probably isn't the best idea, but it will work for now.
Your answer
Follow this Question
Related Questions
Iterate an array 4 by 4 1 Answer
Coroutine being iterated in an unrelated function 0 Answers
Help doing mouse click changin shader and back to normal to a gameObject ꜛ! 1 Answer
How to determine what type of class is being interated through in an array of multiple classes 1 Answer
how do I generate a drop-down list of functions on scripts attached to a game object? 1 Answer