How can I assign references to GameObjects through a script?

For context, a little info about my game. When I press a key, the character in my game (an iteration of the Player Prefab) is supposed to send out an oblong child object (absorberPrefab), after which the player prefab is destroyed.

var absorbTransform = Instantiate (absorberPrefab) as Transform;

absorbTransform.position = transform.position;

Destroy (gameObject);

If this object collides with an enemy, the player gains control of the enemy by the enemy gaining the controller scripts.

public class BasicEnemyScript : MonoBehaviour {

void OnTriggerEnter2D (Collider2D player1Collider) {

	AbsorberScript absorber = player1Collider.gameObject.GetComponent<AbsorberScript> ();

	print ("hit");
	gameObject.AddComponent<Player1> ();

If it misses, another instance of the player is instantly created.

My problem is that I have a camera following script with a variable

public Controller2D target;

which I normally have to so assign to my player gameObject via drag-and-drop in the inspector.

However, if I’m controlling new gameObjects or creating new instances of the Player prefab, I need to a way to assign the camera to follow these during runtime. How can I assign these variables during runtime?

Similarly, is there a way I can create scripts or components so that they will always take in the same variable references automatically, no matter what they’re assigned to (eg. a camera script that will always target the current instance of the player prefab)?

Thank you!

Under ‘Static Functions’

Hi there,
I may be late but just in case someone has same issue. my solution comes in two parts

1- you can use a Scriptable Object to hold a reference to the prefab i e: public GameObject[] myPrefabs;
then assign the values to the list on the inspector this way you’ll have a persistent refrence to the prefabs so instantiate won’t return a null object when spawning the absorber nor the player.

2- while you do need a reference to the prefab, you also need to set the the reference to the camera’s property “public Controller2D target;” given that you’re player spawns correctly you can attach its transform to the camera like this:

//assign back a ref to the player prefab
    Player player1 = Instantiate (myScriptableobject.myPrefabs[0],     gameObject.transform.position,     gameObject.transform.rotation);
    //find the camera or or create another property that hold the ref to the camera
    Camera mycam =  Instantiate (myScriptableobject.myPrefabs[1], myScriptableobject.myPrefabs[1].transform.position, myScriptableobject.myPrefabs[1].transform.rotation) ; =;
    //assuming the target is a variable on the playerScript or a property