我正在Unity中快速制作2人游戏,我想到了这一点:
using UnityEngine;
using System.Collections;
public class PlayerClient : MonoBehaviour {
public string username;
public RaceType currentRace = RaceType.Human ;
GameObject playerMob;
Player currentPlayer;
ClientController attachedController;
// Use this for initialization
void Start () {
attachedController = gameObject.GetComponent (typeof(ClientController)) as ClientController;
if(attachedController == null)
Debug.LogError("Could not create attachedController!");
}
// Update is called once per frame
void Update () {
}
public void MovementInput(float x, float y, float z){
playerMob.transform.Translate (x, y, z);
}
public void FinishCharacterCreation(){
switch (currentRace) {
default:
break;
case RaceType.Human:
playerMob = Instantiate (Resources.Load ("Human", typeof(GameObject))) as GameObject;
currentPlayer = playerMob.AddComponent<Player> () as Player;
attachedController.enabled = true;
break;
}
}
}
其中有3个班级;
PlayerClient
,Player
和ClientController
。显示的一个是PlayerClient(显然)。播放器是一个空白(此时),ClientController只是与网络结合使用的基本内容。
我收到此错误:
[NullReferenceException:对象引用未设置为对象的实例]
在第24和34行上,您将看到引用了playerMob(只是一个空白的3d立方体)和AttachedController的行。据我所知,它们似乎没有保存到已定义的变量中,但是在第32和33行中没有错误,因此看来它只是保存到一个仅具有该功能的临时变量中,而不是类中变量(成功制作了“人类”预制件)。
我觉得自己犯了一个简单但根本的错误,但是我无法终生将其束之高阁。
我尝试从播放器中删除monobehaviour继承,并使用new()关键字而不是实例化它,但是发生了同样的事情。我做错什么了?
编辑:这是我做的一点测试。
using UnityEngine;
using System.Collections;
public class Client : MonoBehaviour {
string username;
Player player;
GameObject playerMob;
ClientController clientController;
// Use this for initialization
void Start () {
clientController = gameObject.GetComponent( typeof(ClientController) ) as ClientController;
if(clientController == null){
Debug.LogWarning("Client Controller is null!");
} else {
Debug.LogWarning ("Client Controller is NOT null!");
}
}
// Update is called once per frame
void Update () {
}
public void FinishCharacterCreation(){
player = new Player ();
if (player == null) {
Debug.LogWarning ("Player is null!");
} else {
Debug.LogWarning ("Player is NOT null!");
playerMob = Instantiate (Resources.Load ("Human", typeof(GameObject))) as GameObject;
}
if (playerMob == null) {
Debug.LogWarning ("PlayerMob is null!");
} else {
Debug.LogWarning ("PlayerMob is NOT null!");
}
if (clientController == null) {
Debug.LogWarning ("ClientController is null!");
} else {
Debug.LogWarning ("ClientController is NOT null!");
}
}
}
调试日志警告无处不在。播放此视频时,我得到的是:
Client Controller is NOT null!
Player is NOT null!
PlayerMob is NOT null!
ClientController is null!
注意最后的日志。为什么会这样呢?设置了clientController变量后,显然会调用FinishCharacterCreation()。除了您在此处看到的脚本和对象之外,所有脚本和对象都是完全空的。 (Player不是monobehaviour固有的,ClientController是固有的)。FinishCharacterCreation()由UI按钮调用,并且Client附加的GameObject是由基本NetworkManager对象制成的预制件。
最佳答案
何时调用FinishCharacterCreation?可能在Start之前调用FinishCharacterCreation,这将导致AttachedController为null。实例化gameObject时,可能要花费一两个帧才能调用Start,因此您可能过早地调用了FinishCharacterCreation。我将放置一些Debug.Logs,并确保按照您期望的顺序调用所有函数。