Work around for referencing player for prefab script

I’m busy making a game were I want missiles to follow the player.

To do this I made a script called AttackPlayer which I added to the missile prefab. AttackPlayer takes a public gameObject variable to get the player gameobject to access its position.
But Unity won’t let me drag and drop any game objects apart from prefabs themselves.

The problem with this is that I want to get the players position in the game, and if I reference the prefab itself it only gets the preset position of the prefab, not the instantiated prefab in the game.

Does anybody know a work around for this?

In cases like this you should think of prefabs just like any asset or file that exists in a folder, i like to think of prefabs as Prefabricated (hense the name prefab) “dead” GameObjects, they aren’t bound to any scene or runtime , they are just a “receipe” for a gameobject and not a live one.

Just remember that when you drag a prefab in a scene your saying “hey , i want to have a gameobject that looks like this one” your not putting the actual prefab in the assets folder, just a replica.

Now for the work around, you can have a “Spawner” script that takes care of creating the instance of the prefab AND setting the correct reference to the player, something like this

MissileSpawner.cs

public class MissileSpawner : MonoBehaviour
{ 
    [SerializeField]
    // reference to the missile prefab in the assets folder
    private MissileBehaviour missilePrefab;
    
    // reference to the player in the scene
    [SerializeField]
    private PlayerBehaviour playerReference;
    
    public MissileBehaviour Spawn() 
    {
        // here we take that missile prefab and make a replica of it
        MissileBehaviour newMissileInstance = Instantiate(missilePrefab);
        
        // since the spawner already has a reference to player , it can pass it to the new missile
        newMissileInstance.player = playerReference;
        
        return newMissileInstance;
    }
}