본문 바로가기
XR/Unity3D

Unity - 여러개의 태그로 가장 가까운 물체 찾기

by -솔솔- 2018. 9. 30.
반응형

using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class haptic : MonoBehaviour {

public Transform target;

private float dist;

private string[] tags = {"static_wall", "dynamic_wall"};

GameObject[] taggedWalls = {};

// Use this for initialization

void Start () {

Debug.Log("start haptic");

}


// Update is called once per frame

void Update () {

if(target != null)

{

Debug.DrawLine(transform.position, target.position, Color.yellow);

}


float closestDistSqr = Mathf.Infinity;

Transform closestWall = null;


foreach (string tag in tags)

{

GameObject[] taggedWalls = GameObject.FindGameObjectsWithTag(tag);


foreach(GameObject taggedWall in taggedWalls)

{

Vector3 objectPos = taggedWall.transform.position;

dist = (objectPos - transform.position).sqrMagnitude;


if(dist < closestDistSqr)

{

closestDistSqr = dist;

closestWall = taggedWall.transform;

}


}

target = closestWall;

}


}


}



댓글