I’m making a multiplayer game in unity using Netcode for Gameobjects. I allowed each player to have their own camera that follows them. The system worked fine. However, when I disabled it to do some debugging for something else, and then reenabled it, suddenly I get an error, because the camera holder variable isn’t assigned. The thing is, I want that variable to be assigned in the code, when the player instantiates their own camera holder. I can’t set it to private, because I need another script to access it, and I can’t make it local, because multiple functions need it. Here are the scripts (they’re both assigned to the player):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Unity.Netcode;
public class CamController : NetworkBehaviour
{
public float rotationSpeed;
public float lerpSpeed;
public GameObject camHolder;
private Camera playerCamComp;
private GameObject playerCam;
public Player PlayerScr;
void Start()
{
camHolder = PlayerScr.camHolder;
playerCamComp = camHolder.GetComponentInChildren<Camera>();
playerCam = playerCamComp.gameObject;
}
void FixedUpdate()
{
//Camera is rotatable with left and right keys
float camInput = Input.GetAxis("MoveCam");
camHolder.transform.Rotate(Vector3.up, camInput * Time.deltaTime * rotationSpeed);
//Camera moves and looks at the player
camHolder.transform.position = Vector3.Lerp(camHolder.transform.position, transform.position, lerpSpeed * Time.deltaTime);
playerCam.transform.LookAt(this.transform);
}
}
Second:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Unity.Netcode;
public class CamController : NetworkBehaviour
{
public float rotationSpeed;
public float lerpSpeed;
public GameObject camHolder;
private Camera playerCamComp;
private GameObject playerCam;
public Player PlayerScr;
void Start()
{
camHolder = PlayerScr.camHolder;
playerCamComp = camHolder.GetComponentInChildren<Camera>();
playerCam = playerCamComp.gameObject;
}
void FixedUpdate()
{
//Camera is rotatable with left and right keys
float camInput = Input.GetAxis("MoveCam");
camHolder.transform.Rotate(Vector3.up, camInput * Time.deltaTime * rotationSpeed);
//Camera moves and looks at the player
camHolder.transform.position = Vector3.Lerp(camHolder.transform.position, transform.position, lerpSpeed * Time.deltaTime);
playerCam.transform.LookAt(this.transform);
}
}
Aside from what I mentioned earlier, I also tried initially assigning some other random prefab that I created for this purpose, but it didn’t work.
1