- Home /
How do I make a GameObject chase the nearest spawned game object?
I want to spawn spheres and make a cube chases them. However, this cube is chasing them in the order that they spawn, not the closest ones. I want to make this cube chase the closest spheres, even if it has to change the direction before getting the sphere that it is currently chasing. Can someone please help me? Thank you. P.S. They spawn more rapidly than the cube can destroy then and the function to destroy the spheres is in another code. { Transform _food; CharacterController _controller;
[SerializeField]
float _speed = 5.0f;
void Start()
{
}
void Update()
{
GameObject foodGameObject = GameObject.FindGameObjectWithTag("Food");
_food = foodGameObject.transform;
_controller = GetComponent<CharacterController>();
Vector3 direction = _food.position - transform.position;
direction.Normalize();
_controller.Move(direction * Time.deltaTime * _speed);
}
}
Put your spawned spheres in a List and than Linq may help you like below:
YOURSPHERESLIST.Sort((x, y) => Vector3.Distance(x.transform.position, YOURCUB$$anonymous$$transform.position).CompareTo(Vector3.Distance(y.transform.position, YOURCUB$$anonymous$$transform.position)));
With this line of code your spheres will be sorted from nearest to furthest. So YOURSPHERESLIST[0] will be the closest one which you want to chase in this case. But i must warn you this cost too much performance. So i suggest you to sort your objects when a new one spawned not per frame. And try not even using Linq this much if you are dealing with mobile platform.
And one more suggestion try not to destroy your objects if you dont have to but store them somewhere and activate/deactivate them when you need to use them.
post the code that is spawning and we can help more specifically
Answer by Arshio_boss · Mar 20, 2019 at 07:50 AM
have you tried using the rigid body of the one chasing the spawned object? you could do rigidbody.Addforce(new vector 3(x,y,z)); or you could try making the one chasing the spawned object a child of it
Your answer
![](https://koobas.hobune.stream/wayback/20220612075011im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
FindClosestEnemy gives Error CS0165: Use of unassigned local variable 'closest' 2 Answers
How to target closest enemy, but with a min/max range 1 Answer
how to find the closest (and second closest) object with tag - one object 4 Answers
Spawn a prefab at the closest GameObject with one of four relevant tags. 1 Answer
Overlap Sphere detecting itself 1 Answer