Suppose the script finds the center point between two objects on the map.

public List<Transform> targets;

 Vector3 GetCenterPoint() { if (targets.Count == 1) { return targets[0].position; } var bounds = new Bounds(targets[0].position, Vector3.zero); for (int i=0; i < targets.Count; i++) { bounds.Encapsulate(targets[i].position); } return bounds.center; } 

But how to make finding a center between objects, if they only appeared on the map? How to create a prefab on the map:

 if (!spawned) { if (Input.GetKey(KeyCode.Q)) { Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity); spawned = true; } } 
  • one
    obviously, you need to update the `targets` values ​​after creating the object .. - Stranger in the Q

1 answer 1

Apparently you need when creating a new object, add it to your targets list. You can do it like this:

 if (!spawned) { if (Input.GetKey(KeyCode.Q)) { var newTarget = Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity); targets.Add(newTarget.transform); spawned = true; } } 

Thus, all the matched objects will be taken into account when getting the center point in the method that you wrote above.

  • Thank you very much, but how can you then delete it from the list? - Yaroslav Smirnov
  • I have an empty object at the point (0, 0, 0), inside the object are the Canvas and the model of the tank. The camera is tracking an empty object (which does not move). How to make the camera watching the model of the tank? - Yaroslav Smirnov
  • @ Yaroslav Smirnov, you can remove an object from a sheet like this: targets.Remove ( your_object ); - Mikhail Deyman
  • @ Yaroslav Smirnov, so that the camera monitors the child, i.e. in your case behind the tank, it is obvious that you need to transfer to the camera not the parent object (an empty non-moving object), but the tank itself. If you add more code, maybe I can help. - Mikhail Deyman 7:54 pm
  • Well, according to your script, a prefab (empty object) is created and immediately entered into the list of monitored objects. How to create a parent object, but track the model that is inside it? - Yaroslav Smirnov