Camera follow Instantiated Photon multiplayer player

I have this script attached to my camera:

public class CameraFollow : MonoBehaviour {

    public Transform target;

    public float smoothSpeed = 0.125f;
    public Vector3 offset;

    private void Start()
    {
        target = ?        
    }

    private void LateUpdate()
    {
        transform.position = target.position + offset;
    }
}

Since my player is instantiated, I can not drag the prefab to the public target. What can I type in the Start function go set the target as my instantiated player. It has the tag "Avatar".

I am using PhotonNetwork, so I will have several players in a room.

1 answer

  • answered 2018-11-08 11:01 SwiftingDuster

    One way is to modify Start() to:

    private void Start()
    {
        GameObject[] players = GameObject.FindAllGameObjectsWithTag("Avatar");
        foreach (GameObject player in players)
        {
            if (PhotonView.Get(player).isMine)
            {
                this.target = player.transform;
                break;
            }
        }
    }
    

    This with the assumption that your player class inherits from Photon.MonoBehaviour if it isn't already.

    PhotonView.Get(player).isMine checks whether the network object is owned by your client, which would therefore be able to differentiate between your player and another person's player. Once you have found the reference to your own player, you can assign it as the camera's target.