Problem with "Camera follow after Spawn player".

Hi!

I’ve got a problem witch ‘Camera follow’

So, when i had my ‘player’ on the game map in some place just teleport him when i start the game. And camera works fine, follow by player, etc…

But, i had an idea, create ‘player’ as prefab, create new script ‘spawn’ and use Instantiate to spawn character on the game map.

Then my camera was broken. Character was spawned at correct place, but my camera still look at 0, 0, 0 coords and stop follow my player.

There is my spawn and camerafollow script’s:

CameraFollow

public Transform player;
Vector3 position;
Vector3 diff;

void Start ()
{
    position = new Vector3(10, 10, 10);
    transform.position = player.position + position;

    diff = transform.position - player.position;
}

void Update ()
{
    transform.position = player.position + diff; 
}

and SpawnPoint

public GameObject spawnPlayer; 

// public Transform startPoint; 

void Start()
{
    //transform.position = startPoint.position;
    spawnPlayer = (GameObject)Instantiate(spawnPlayer, transform.position, transform.rotation);
}

void Update()
{

}

Without using Instantiate works fine.
Im not expert in c# programming but still studying :stuck_out_tongue:

PS. Im from Poland and sorry for my language.

it seems like your camera does not have a target if you instantiate the player. when the player was not a prefab but calmly sitting in the hierarchy there was no problem because (i assume) you dragged the player-object into the corresponding camera-target slot in the inspector. all good.

but as soon as you remove the player from the hierarchy and make him a prefab. your camera does not know who to follow even though a player might be spawned later on.

to solve this little riddle you have to tell your camera to look for a player if it has no target to follow. dumb lazy camera.

you might try to do the following:

  1. select your player prefab - top line on inspector dropdown menu “TAG” - select “Player”

  2. add this to the update function of your camera

    if (!target) {
    target = GameObject.FindGameObjectWithTag("Player").transform;
    }
    
  3. add this to the start function of your camera

         if (!target) {
         target = GameObject.FindGameObjectWithTag("Player").transform;
         }
    

i hope i made no mistake and it works for you (:

Hi, thanks for quick respond :wink:

In my last script, i’ve had something like that:

target = GameObject.FindWithTag(“Player”).transform.position;

But it didn’t work well. I knew why my camera stops track my player, but i didn’t know how to repair this.

I hope that using:
target = GameObject.FindGameObjectWithTag(“Player”).transform;
will help.

Thanks! :slight_smile: /

Thank you so much!!! I was having this error and couldn’t figure out how to fix it, then I read this and applied what you said; it was fixed instantly! Thank you!