- Home /
Raycasting2D to Compare Tag of GameObject
Hello, I'm attempting to use raycasting to detect if an object is in the top of the scene. In the images below you will see an orange button. When the orange button is pressed, I want any objects tagged "Word Card" to be destroyed. I figured I could do this by using raycast to draw a ray to the red target circle (see picture). But it seems I am having difficulties getting it to work. Does anyone have any suggestions? I've heard Linecasting is a better approach but I have not been able to figure that out either. Any advice is greatly appreciated! Thanks! - Comic!
Here is my current code
public Transform deleteLine;
private RaycastHit2D Hit;
private void OnMouseDown()
{
Debug.Log("Clicked Delete Button");
if (Physics.Raycast(transform.position, deleteLine.position))
if (Hit.collider.CompareTag("WordCard"))
{
Debug.Log("WordCard Will be Deleted");
}
}
Answer by nrgger · Jun 30, 2017 at 09:40 AM
You can get all GameObjects in scene tagged "Word Card" and than destroy it all. You can use this code: public string myTag;
private void OnMouseDown()
{
DestroyObjects(myTag);
//any other thing you want
}
public void DestroyObjects(string withTag)
{
GameObject[] gameobjects = GameObject.FindGameObjectsWithTag(withTag);
foreach (GameObject g in gameobjects)
Destroy(g);
}
You should also be careful with tags (check capital letters and whitespace), Word Card, WordCard and word card are different tags. I hope i've been clear and useful.