How to instanciate transform to element of a list?,How Get Transform of a instanciated Prefap

Hi im using this code for target two objects with the main camera but i have a problem, mi first object needs to destroyed, so when is destroyed is instanciated a new prefap but de instance of the transform is breacked i tried to find gameobjects with tag but i dont know how set transform to my first gameobject of the list. (Sorry for my english if you dont understand i´ll try to be more clear)

public List<Transform> targets;
public Vector3 offset;
private Vector3 velocity;
public float smoothTime = 0.5f;



 void Update()
{
    GameObject Player;
   Player =  GameObject.FindGameObjectWithTag("Player");
    if (Player == null)
    {
        //instanciate transform to my first element of the list in this case Element 0.
    }

}

void LateUpdate()
{
    if (targets.Count == 0)
        return;

    Vector3 centerPoint = GetCenterPoint();

    Vector3 newPosition = centerPoint + offset;

    transform.position = Vector3.SmoothDamp(transform.position,newPosition, ref velocity, smoothTime);
}

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*.position);*

}
return bounds.center;
}
}

So to be clear, you want to set the new player’s transform to the last destroyed object? Or am i missing something?

@CommodoreClutch yeah that´s all only i want to set the new player transform to target the main camera

Hi @unity_x4cLljwYc55zWA ,

As far as I can understand from your post you want to Instantiate an object and then add this object to a list.


Instantiate is a function with a return type. This means you can assign this return value when you instantiate the object.

GameObject obj = (GameObject)Instantiate(prefab, position, rotation);

The normal return type of the Instantiate function is the “Object” type. we don’t really want to use this type right now so we can cast it to another type. This is what the (GameObject) in front of the Instantiate call is for. Another way to do it is to add

as GameObject;

At the end of the Instantiate call. This can also be done to receive the return value as a Transform.


You want to assign this objects transform to a list. There’s multiple ways about this but I’ll show you the one I personally prefer.

Transform transform = (Transform)Instantiate(prefab, position, rotation);

list.Add(transform);

//Or:

List.Add((Transform)Instantiate(prefab, position, rotation));

I hope this helps! If you have any questions feel free to ask.


Wybren van den Akker