I'm building a custom triangular grid for my game and using the object names for the coordinate system. I put this code in update to try to gather the name for the object I click on.
My primary behavior script in the OnMouseOver
method, keeps changing the tilehome
variable to the name of the gameObject my mouse moves over. I can tell the behavior is caused because I'm referencing gameObject.name
directly, but I have no idea how to gather this information with a mouse click once and hold it in a variable to use in my OnMouseOver
method.
I tried using a bool
to prevent it from changing, but the reference variable obviously doesn't work that way. How do I get the object name from my clicked object to remain static in my OnMouseOver
method once I capture it?
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if(tileanchor == false)
{
tileanchor = true;
tilehome = gameObject.name;
}
}
if (Input.GetMouseButtonDown(1))
{
tileanchor = false;
}
}
I used Debug.Log
to see that it is updating my tilehome
variable every time my object focus changes in my OnMouseOver
method. I tried moving the tilehome
to the OnMouseOver
method, but it had the same problem. I feel like I need a different type of object reference or something? Any help would be appreciated!
You can use the following method.
RaycastHit hit;
void Update()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 2f))
{
string objName = hit.collider.gameObject.name;
Debug.Log("object that was hit: " + objName);
}
}
}