Однако, когда я отключил ее для отладки чего-то другого, а затем снова включил, внезапно я получил сообщение об ошибке, поскольку переменная держателя камеры не назначена :
NullReferenceException: ссылка на объект не установлена на экземпляр объекта
CamController.Start () (в Assets/Scripts/ CamController.cs:19)
и
NullReferenceException: ссылка на объект не установлена к экземпляру объекта
CamController.FixedUpdate() (в Assets/Scripts/CamController.cs:31)
Дело в том, что я хочу, чтобы эта переменная была назначена в коде, когда игрок создает экземпляр своего собственного держателя камеры. Я не могу сделать его частным, потому что для доступа к нему нужен другой скрипт, и я не могу сделать его локальным, потому что он нужен нескольким функциям.
Вот скрипты (они оба назначены игроку):
Код: Выделить всё
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class Player : NetworkBehaviour
{
private Rigidbody playerRb;
public GameObject camHolderPrfb;
public GameObject camHolder;
public float speed;
public float jumpForce;
public float gravityMod;
private bool onGround = true;
void Start()
{
camHolder = Instantiate(camHolderPrfb, transform.position, Quaternion.identity);
playerRb = GetComponent();
Physics.gravity *= gravityMod;
}
void Update()
{
//Makes sure player can only control its character
if (!IsOwner) {enabled = false;}
//Calculates player movement
float forwInput = Input.GetAxis("Vertical");
float horzInput = Input.GetAxis("Horizontal");
Vector3 direction = camHolder.transform.forward * forwInput + camHolder.transform.right * horzInput;
//Applies movement to player
if (direction.magnitude > 1) {direction.Normalize();}
playerRb.AddForce(direction * speed);
//Allows player to jump
if(Input.GetKeyDown(KeyCode.Space) && onGround) {
onGround = false;
playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
//Ensures player can only jump if it's touching the ground
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground")) {
onGround = true;
}
}
}
Код: Выделить всё
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();
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);
}
}
Подробнее здесь: https://stackoverflow.com/questions/788 ... n-the-code