- Home /
Click Twice To Confirm
I need to know how you make a script hold an object where the mouse is after one click and then place it if the button has been clicked again.
I have tried by putting an if statement inside another one but as they are in void update they both are checked instantly so they wont wait for the second confirmation.
Here is the code i have tried
public GameObject NRGLaserTransfer;
int layerMask = 1 << 8;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, layerMask))
{
Vector3 kordinater = new Vector3(hit.point.x, 0, hit.point.z);
Quaternion rotation = new Quaternion();
Instantiate(NRGLaserTransfer, kordinater, rotation);
bool bygger = true;
if (Input.GetMouseButtonDown(0) && bygger == true)
{
Debug.Log("Hit " + hit.point);
}
}
}
}
}
Answer by AltaNox · Jan 07, 2020 at 05:43 PM
Remember that Update gets called every frame. If your game is running at 60 FPS then that's 60 times every second. You cannot check for the same Input twice in the same frame because, like you've already noted, you're gonna get the same result no matter what.
What you want is to catch an input at a certain frame. Then in some future frame catch the input again to see if it was clicked twice. You could also put a time limit between those 2 clicks if you want to consider it as a double click or you couldn't it's up to you.
So here's some code
private int clickCount;
int layerMask = 1 << 8;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, layerMask))
{
clickCount++;
if (clickCount == 2)
{
//Do what you want here
}
}
}
}
What this code does is to count the clicks. When 2 clicks are registered then it will do something, whatever you put inside that last if check.
What this code doesn't do: It doesn't take time into account. So the second click can come a second later or an hour later, it will execute no matter what. It won't work more than once because the counter is not being reset.
Your answer
Follow this Question
Related Questions
GUI.Button on MouseHover 1 Answer
If mouse is hovering over any GUI element 0 Answers
How can i disable left button mouse, when i click on GameObject? 2 Answers
Menu button needs to be double clicked. 4 Answers
How to detect if mouse over a button 2 Answers