I have 4 different tags that I add to a list to know possible spawn locations for my object.
public List<GameObject> locationsToSpawn = new List<GameObject>();
locationsToSpawn.AddRange(GameObject.FindGameObjectsWithTag("tag1"));
locationsToSpawn.AddRange (GameObject.FindGameObjectsWithTag("tag2"));
locationsToSpawn.AddRange(GameObject.FindGameObjectsWithTag("tag3"));
locationsToSpawn.AddRange(GameObject.FindGameObjectsWithTag("tag4"));
I want to spawn an new object on the edge of the GameObject in the scene that is closest to my click.
if (Input.GetMouseButtonDown(0))
{
clickPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
closestObject();
if(closest.tag == "tag1")
{
objectSpawnPosition = closest.transform.position;
GameObject objectInstance = Instantiate(spawnUpPrefab, objectSpawnPosition, Quaternion.Euler(new Vector3(0, 0, 0)));
}
//repeated for the 3 other tags.
}
This is how I find the closest object (largely stolen from unity documentation)
public GameObject closestObject()
{
float distance = Mathf.Infinity;
foreach (GameObject go in locationsToSpawn)
{
Vector3 diff = go.transform.position - clickPosition;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
I have two major problems. It doesn’t always spawn on the closest object, almost ignores tag1 even when pressing directly on that object when one of the others are nearby. Also, I can’t figure out how to properly spawn on the edge, as of now I use objectSpawnPosition.y = closest.transform.position.y + A.BCf; to correct the positioning but I feel like there should be a more effective or more precise way.
Thank you!