I’m writing a piece of code that finds all objects on the field with a certain tag and puts it into to an object array.
After that, the array is put into a function I found that finds the object which is closest to object this script is attached to.
Only problem is that GameObject.FindGameObjectsWithTag (“TagName”); returns an object array, and the function i found only takes a transform array.
Is there anyway i can convert an object array into a transform array so that i can use this function?
This is what the code looks like right now:
using UnityEngine;
using System.Collections;
public class GetClosestCube : MonoBehaviour {
// Use this for initialization
public Object[] respawns;
void Start () {
respawns = GameObject.FindGameObjectsWithTag ("Respawn");
Debug.Log (respawns.Length);
}
// Update is called once per frame
void Update () {
GetClosestEnemy (respawns);
}
Transform GetClosestEnemy(Transform[] enemies)
{
Transform tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;
foreach (Transform t in enemies)
{
float dist = Vector3.Distance(t.position, currentPos);
if (dist < minDist)
{
tMin = t;
minDist = dist;
}
}
return tMin;
}
Why can’t you just change the method signature to:
Transform GetClosestEnemy(GameObject[] enemies)
If you must keep the argument the way it is, here’s how you’d do it:
using UnityEngine;
using System.Collections;
public class GetClosestCube : MonoBehaviour
{
// Use this for initialization
public Transform[] respawns;
void Start ()
{
GameObject[] respawnObjects = GameObject.FindGameObjectsWithTag ("Respawn");
respawns = new Transform[respawnObjects.Length];
for ( int i = 0; i < respawns.Length; ++i )
respawns _= respawnObjects*.transform;*_
Debug.Log (respawns.Length); }
// Update is called once per frame void Update () { GetClosestEnemy (respawns); }