Adding Multiple Tags to a GameObject[] Array
I have a method used to locate the nearest gameobject tagged "searchTag" to a touch position, but I need this to work for multiple tags. If possible I would like to create a gameobject array from gameobjects of multiple tags and use that in the foreach loop. I have looked around and cant seem to find anything to accomplish this in C#. Any help is appreciated!
void GetNearestTaggedObject()
{
Touch touch = Input.GetTouch(0);
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 8));
float nearestDistance = Mathf.Infinity;
GameObject[] taggedGameObjects = GameObject.FindGameObjectsWithTag(searchTag);
Transform nearestObj = null;
// loop through each tagged object, remembering nearest one found
foreach (GameObject obj in taggedGameObjects)
{
Vector3 objectPos = obj.transform.position;
float distance = Vector3.Distance(objectPos, touchPosition);
if (distance < nearestDistance)
{
nearestObj = obj.transform;
nearestDistance = distance;
}
}
nearestObj.gameObject.tag = "Moving";
}
Comment