- Home /
How to print the vector position of the mouse constantly?
So I created a simple script attached to the camera that allows me to see the position of the mouse via the console menu. However, it only provides me with the origin position when I clicked the mouse button down.
What I want the script to do is to constantly update the position every 2 seconds while the mouse button is pressed:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CursorPosition : MonoBehaviour
{
public GameObject particle;
IEnumerator Wait()
{
yield return new WaitForSeconds(2);
}
void Update()
{
while (Input.GetMouseButton(0))
{
StartCoroutine(Wait());
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log(ray);
else break;
}
}
}
However, the while loop seems to be looping infinity and crashes unity when I try to run the script.
I feel like my logic is inconsistent, perhaps I am approaching the problem incorrectly?
Answer by bakir-omarov · Jun 09, 2018 at 08:06 AM
Just add some bool for your script, and change the value of bool every 2 secs. Hope it will help:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CursorPosition : MonoBehaviour
{
public GameObject particle;
private bool timerIsON; // bool for timer
IEnumerator Wait()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log(ray);
yield return new WaitForSeconds(2);
timerIsON = false;
}
void Update()
{
if (Input.GetMouseButton(0) && !timerIsON)
{
timerIsON = true;
StartCoroutine(Wait());
}
}
}
Your answer
Follow this Question
Related Questions
Why print() only print the same string once? 1 Answer
How can I use "print" from within a custom class? 2 Answers
How to print Byte 1101010 version of a float? 1 Answer
Debug.Print not working 3 Answers
print(); to console problem - beginner 0 Answers