Johnny Lin
Johnny Lin

Reputation: 11

How to reference local instance of main camera in unity networking when there is more than one in the scene. One per player

I'm making a game in multiplayer game in unity that uses the network. It uses network manager, network manager HUD and network identity. Probably more components as I learn more about unity. The problem is, the main camera spawns in the menu before my player object spawns through network manager. So the lookAt variable isn't properly assigned. I want to assign it either through the camera script or player script after the player has spawned. The problem is that there are 4 players prefabs and 4 main cameras in the game when its up and running. Everything I've tried just reassigns ALL the camera's lookAt variables. How do I assign my just my local camera's lookAt to my local player?

Upvotes: 1

Views: 1211

Answers (1)

Remy
Remy

Reputation: 5163

Don't use a main Camera for every player, there should always only be 1 main camera active in your scene at any given time (hence it being called main camera). So if you try to make a call to Camera.Main it will all your main cameras, and not just the player's.

I think the best way to achieve what you want is to make a prefab of a camera (that is not tagged as MainCamera and put your camera script (if you have one) or any other components you want on your camera on that prefab aswell.

Then when your player spawns you instantiate the prefab to make an instance of the camera prefab ment for that player alone, and using the LookAt only on the instanced camera for that player

It would look something like the following:

public GameObject cameraPrefab; //prefab of the camera you want to instance
private Camera playerCam; //this is gonna be a reference to the camera that looks at the player
void SpawnPlayer()
{
    playerCam = Instantiate(cameraPrefab).GetComponent<Camera>(); //instantiate the cameraPrefab and get the camera component of it
    playerCam.transform.LookAt(transform); //get the transform of the instanced camera to look at the transform on which this script is run (In this case assuming your player)
}

Upvotes: 1

Related Questions