I have 2 tagged gameobjects, and I would like a gameobject (which has the script below attached to it) to move to the closest gameobject that has the tag. However, it doesn’t. Please can someone kindly tell me why? Thanksenter code here
using UnityEngine;
using System.Collections;
public class moveBomb : MonoBehaviour
{
public GameObject object1;
private GameObject[] objects1;
private GameObject nearestTarget;
private float distance;
private float curDistance;
private Vector3 pos;
private Vector3 diff;
private float speed = 1.5f;
// Use this for initialization
void Start()
{
nearestTarget = null;
distance = Mathf.Infinity;
pos = transform.position;
objects1 = GameObject.FindGameObjectsWithTag("target");
FindClosesttarget();
}
void FindClosesttarget()
{
foreach (GameObject obj in objects1)
{
diff = obj.transform.position - pos;
curDistance = diff.sqrMagnitude;
if(curDistance < distance)
{
nearestTarget = obj;
object1 = nearestTarget;
distance = curDistance;
}
}
}
// Update is called once per frame
void Update()
{
if (object1 != null)
{
transform.position = Vector3.MoveTowards (transform.position, object1.transform.position, speed);
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "target")
{
Destroy(transform.gameObject);
}
}
}