- Home /
Get main cam from player after player was spawned
So I'm making a multiplayer game for a Uni project and i have a buildingSystem script, where I need to set the main cam of the first person character to be able to see the building previews. The problem is, the players are spawned after the game ist started, so I cannot drag the camera from the scene to the script in the inspector. How could I get the camera to be added to the inspector after the game was started and the player spawned?
so this is my player prefab
and this is my BuildSystem game object where the buildSystem script is in.
This is fart of the buildSystem script:
private void DoBuildRay()//actually positions your previewGameobject in the world
{
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);//raycast stuff
RaycastHit hit;
if(Physics.Raycast(ray,out hit, 100f, layer))//notice the layer
{
float y = hit.point.y + (previewGameObject.transform.localScale.y / 2f);
Vector3 pos = new Vector3(hit.point.x, y, hit.point.z);
previewGameObject.transform.position = pos;
Answer by Hristo_Kalinov · May 15, 2020 at 11:50 AM
@Frank07101997 You said you are making a multiplayer game so there will be a lot of Cameras with the same names so you should use "Transform.GetChild". https://docs.unity3d.com/ScriptReference/Transform.GetChild.html
Transform Camera;
void Start()
{
//Get the first child of the object in the hierarchy.
Camera = gameObject.transform.GetChild(0);
Debug.Log(Camera);
}
Attach this script on the player. Note that this script will get the first child of the object in the hierarchy so make sure the Camera is the first child. I hope this was helpful. This is my first answer here
Answer by wewewu · May 16, 2020 at 07:17 AM
You can use Camera.main to get the main camera, it would look like this:
private Camera cam;
void Start()
{
cam = Camera.main;
}
Your answer

Follow this Question
Related Questions
Main Camera Stops working or just freezes? 0 Answers
i need help about players hands positions in 2D multiplayer card game 0 Answers
Multiplayer camera please help 2 Answers
Centering camera between 4 players 2 Answers
Adding Multiplayer functionality 0 Answers