Instantiate multiple objects that follow the FirstPersonController

I’m trying to make a multitude of instantiated objects that will follow my FirstPersonController around when I walk. This FristPersonController has a capsule object as a child, so the character has some visibility.

For this, I have a gameBrain with the following script assigned to it:

public class gameBrain : MonoBehaviour {

	void Start () {
		GameObject prefab = Resources.Load ("EthanScript") as GameObject;

		for (int i = 0; i < 100; i++) {
			GameObject go = Instantiate (prefab) as GameObject; 
			go.transform.position = new Vector3 (i*0.10f, 0, i*2); 
		}
	}
}

The object EthanScript has a script attached to it that makes it follow any object you assign to it.

public class LootAtFollow : MonoBehaviour {

	public Transform myTarget; 

	public float mySpeed = 10.0f; 
	public float epsilon = 0.1f; 
	
	void Update () {
		transform.LookAt (myTarget.position); 

		if ((transform.position - myTarget.position).magnitude > epsilon) {
			transform.Translate (0.0f, 0.0f, mySpeed * Time.deltaTime); 
		}
	}
}

Now I want to immediately assign the capsule that is my controller to the instantiated objects. How do I access the capsule (child of Controller) in code and assign it to be the myTarget? I would like this to be done in code, because I don’t want to have to drag and drop the capsule a hundred times into the myTarget slot in the Inspector.

I tried multiple things but keep running into multiple errors. I hope someone has a tip for me! Thanks in advance!

Hello!

Yo uare very close! YOu need to do this (you can assign the variable directly from GameBrain right after instantiate! You need to use the function transform.find to get the child (lets say the controller Object is called “FPCObject” and the capsule child is called PersonCapsule)

GameObject go = Instantiate (prefab, new Vector3 (i*0.10f, 0, i*2), quaternion.identity ); 
go.GetComponent<LootAtFollow>().myTarget = FPCObject.transform.Find("PersonCapsule");

This will assign the PersonCapsule transform to the myTarget variable right after the prefab is instantiated. You will see that the variable is asigned automatikly before the Start() of LootAtFollow script.

Note FPCObject variable is a GameObject variable, the First person controller gameobject.

Bye!