Search code examples
c#listunity-game-enginedistancegameobject

Find and return nearest gameObject with tag, Unity


im trying to make a game where you have to merge 2 gameObjects to get the next one and so one. First i tried so that when the gameobject is released and it's touching another gameobject it deletes both of those and then instantiates the next one. But this didn't quite work bc of the triggers "covering" each other or some other wierd but. So i thought i could detect the collision so that every gameobject that touches the trigger gets added to a list and then removed on exit. What i'm not trying to figure out is how to calculate the distance between the gameObjects and if they are close enough (mergingthreshold) then they both get destryed and the next gameobject gets instantiated, but i can't quite figure out how to get this distance calculating and returning of what gameObject that is. So all help would be appreciated! (don't leave out any details, cause I'm quite the beginner) Thanks!

Here's the code I've gotten so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Merging : MonoBehaviour
{
    List<GameObject> NearGameobjects = new List<GameObject>();


    void Start()
    { 
    }

    void Update()
    {
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag == gameObject.tag)
        {
            Debug.Log("Enter!");
            NearGameobjects.Add(col.gameObject);
        }
    }


    void OnTriggerExit2D(Collider2D col)
    {
        if (col.gameObject.tag == gameObject.tag)
        {
            Debug.Log("Exit!");
            NearGameobjects.Remove(col.gameObject);
            
        }
    }
}

Solution

  • If you're going to use the list and have added all objects into this list you could use a for each loop and check the distance between your main object and all the other objects in the list if its closer add that to the closets object

        public class NewBehaviourScript : MonoBehaviour {
        List<GameObject> NearGameobjects = new List<GameObject>();
        GameObject closetsObject;
        private float oldDistance = 9999;
    
    
        private void Something()
        {
            foreach (GameObject g in NearGameobjects)
            {
                float dist = Vector3.Distance(this.gameObject.transform.position, g.transform.position);
                if (dist < oldDistance)
                {
                    closetsObject = g;
                    oldDistance = dist;
                }
            }
        }
    
    }