How to make camera follow to clone player not first production?

Viewed 55

I made the code which can follow the clone player in unity. But It worked only the first clone player. If join room second or later, It can't find clone player and doesn't work. How can I fix that ? Thanks for anything your helps.


follow.cs:

private void Awake()
    {
        mainCam = this;
    }

    void Start()
    {
        height = Camera.main.orthographicSize;
        width = height * Screen.width / Screen.height;
    }

    void LateUpdate()
    {
        if (player == null)
        {
            player = GameObject.Find("Player(Clone)");
        }
        else
        {
            //transform.position = new Vector3(target.position.x, target.position.y, -10f);

            transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime * speed);

            float lx = size.x * 0.5f - width;
            float clampX = Mathf.Clamp(transform.position.x, -lx + center.x, lx + center.x);

            float ly = size.y * 0.5f - height;
            float clampY = Mathf.Clamp(transform.position.y, -ly + center.y, ly + center.y);

            transform.position = new Vector3(clampX, clampY, -10f);
        }
    }

player spawn script:

public void Spawn()
{
    GameObject PI = PhotonNetwork.Instantiate("Player", Vector3.zero, Quaternion.identity);
    Follow.mainCam.target = PI.transform;
    
    Debug.Log("I'm in the room.");
}
2 Answers

I guess that player stay null, maybe when you are trying to GameObject.Find() by his name, that method returns null.

Maybe you can try it with a tag or use another name?

The simplest solution is to make the camera the child of the player object and then change it's position accordingly through the script

You could also potentially use CineMachine which has some built-in follow methods

In order to change the parent of an object in the hierarchy through code you basically need to do something like this

public Transform camera 
public Transform player
camera.parent = player;

and you can then set the camera position like this

camera.position = new Vector3(0, 0, -10); 

Since the camera is the child of the player 0, 0, -10 basically means that the camera will be -10 in the Z axis away from the player (which should be behind the player). Whenever the player moves, because the camera is now attached as a child, it will follow the player.

Related