Reputation: 5
I'm currently writing a unity c# script, the main idea is when I click on some part of the model, the part will be highlighted, and now I want it to return to original state by clicking it again. When I click on the same part at the 3rd time, it should be highlighted again.
I don't know how to achieve it inside Update() method, because every click costs several frames and I cannot recognize which frame is the 2nd click, 3rd click, etc.
Is there any way to recognize the number of clicks without considering frames in unity?
void Update(){
if (Input.GetMouseButton(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)){
bone = hit.collider.transform;
if (boneList.Contains(bone) != true)
{
/* if the part is not chosen before, add it to the list and highlight all elements in the list */
boneList.Add(bone);
Highlight(boneList);
}/*cannot delete the element chosen repetitively*/
}
}}
Upvotes: 1
Views: 358
Reputation: 125245
You are so close. The else
statement should be added to your code. Your logic should be like this:
if(List contains clickedObject){
Remove clickedObject from List
UnHighlight the clickedObject
}else{
Add clickedObject to List
Highlight the clickedObject
}
Also, like Serlite mentioned, you have to use GetMouseButtonDown
instead of GetMouseButton
since GetMouseButtonDown
is called once when key is pressed but GetMouseButton
is called every frame while the key is down.
The final code should look like this:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
bone = hit.collider.transform;
if (boneList.Contains(bone))
{
//Object Clicked is already in List. Remove it from the List then UnHighlight it
boneList.Remove(bone);
UnHighlight(boneList);
}
else
{
//Object Clicked is not in List. Add it to the List then Highlight it
boneList.Add(bone);
Highlight(boneList);
}
}
}
}
You have to write the UnHighlight
function which basically restores the passed in GameObject/Transform to its default state.
Upvotes: 4