我对所有播放器使用以下相机脚本(链接)。脚本会放大和缩小以捕获所有玩家。游戏共有4位玩家。现在测试2。我无法使网络播放器的子对象(Kitty_Orange的变换)自动连接到摄像机。
子对象具有Player标记。
https://learn.unity.com/tutorial/camera-control?projectId=5c5149c5edbc2a001fd5be95#5c7f8528edbc2a002053b398
我有一个GameSetupController.cs,可将玩家实例化到场景中。这似乎是将化身的变换添加到相机的最合适的位置。当玩家进入游戏场景时,我会得到一个空引用。
尝试将变换动态添加到Camera m_Targets变换数组时出错。
已调试
Debug.Log("CC.m_Targets.Length" + CC.m_Targets.Length); //Troubleshooting
CC.m_Targets = new Transform[players.Length]; // array of size 1-4
NullReferenceException: Object reference not set to an instance of an object
GameSetupController.CreatePlayer () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:33)
GameSetupController.Start () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:14)
没有调试
CC.m_Targets = new Transform[players.Length]; // array of size 1-4
NullReferenceException: Object reference not set to an instance of an object
GameSetupController.CreatePlayer () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:34)
GameSetupController.Start () (at Assets/InfoGamerPhoton/Scripts/GameSetupController.cs:14)
CameraControl.cs
public Transform[] m_Targets; // All the targets the camera needs to encompass. [HideInInspector]
GameSetupController.cs
using Photon.Pun;
using System.IO;
using UnityEngine;
public class GameSetupController : MonoBehaviour
{
private CameraControl CC;
public GameObject[] players;
// This script will be added to any multiplayer scene
void Start()
{
CC = GetComponent<CameraControl>();
CreatePlayer(); //Create a networked player object for each player that loads into the multiplayer scenes.
}
private void CreatePlayer()
{
Debug.Log("Creating Player");
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PhotonPlayer"), Vector3.zero, Quaternion.identity);
players = GameObject.FindGameObjectsWithTag("Player");
if (players.Length == 0)
{
return;
}
for (int i = 0; i < players.Length; i++)
{
Debug.Log("players.Length" + players.Length); //Troubleshooting
Debug.Log("CC.m_Targets.Length" + CC.m_Targets.Length); //Troubleshooting
CC.m_Targets = new Transform[players.Length]; // array of size 1-4
Debug.Log(CC.m_Targets.Length);
Debug.Log(players.Length);
CC.m_Targets[i] = players[i].transform;
Debug.Log("m_Targets : " + CC.m_Targets[i]);
Debug.Log("players : " + players[i]);
}
}
}
private void FixedUpdate()
{
m_Targets = new List<Transform>();
//ADDS PLAYERS TO THE M_TARGETS LIST!
players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject child in players)
{
//Debug.Log(child.gameObject.transform.GetChild(0));
m_Targets.Add(child.gameObject.transform.GetChild(0));
}
答案 0 :(得分:2)
您的CC对象为null,这是Null引用来自的地方。 GetComponent
将只找到与调用该脚本的脚本相同的GameObject附加的组件。如果在编辑器中将对象静态添加到场景,则可以使用[SerializeField]
属性使私有对象在检查器中可见,并手动分配引用。 Find
方法通常很昂贵,因此,如果您可以通过将引用存储在公共位置或事先进行设置来避免使用它们,则推荐使用这种方法。