- Home /
2D raycasting issues
Hello. I'm trying to use raycasts to get my current mouse position in 2D and display the name of whatever object the mouse is currently above. The issue is sometimes it works sometimes it doesn't and I'm not sure why. Here is my code.
public void DisplayEnemyNames(){
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
_hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
if (_hit == false){
return;
}else
{
if (((1<<_hit.collider.gameObject.layer) & EnemyLayerMask) != 0){
_entityname = _hit.collider.gameObject.GetComponent<NameOfEntity>();
EnemyNameDisplay.text = _entityname.EnemyName;
EnemyNameDisplay.color = EnemyNameColor;
}else
{
EnemyNameDisplay.text = "";
}
}
}
I noticed that only after I edit the box collider for the objects during play-mode it works. If I don't change the box collider it won't work. The NameOfEntity component is just an empty script with a string that I can fill with the name I want to display.
Thank you.
Your answer
Follow this Question
Related Questions
Ray is not being detected 0 Answers
Raycast2D doesn't seem to work correctly. 1 Answer
How come people prefer to use rays for 2d collision instead of edge colliders? 1 Answer
How can i compare Text string from multiple child Text objects? 1 Answer
Is there a convenient way to check if two gameobjects are touching BUT NOT overlapping? 2 Answers