C# 我有一个“UnassignedReferenceException”错误和我的脚本,我不知道如何修复它?
我不断地犯错误 UnassignedReferenceException:EnemyAI的变量player尚未指定 已经分配了。您可能需要为 检查器中的EnemyAI脚本 我对所有这些脚本编写的东西都有点陌生,我试着查看其他论坛,但它们没有任何帮助,但让我更加困惑。以下是脚本:C# 我有一个“UnassignedReferenceException”错误和我的脚本,我不知道如何修复它?,c#,.net,unity3d,C#,.net,Unity3d,我不断地犯错误 UnassignedReferenceException:EnemyAI的变量player尚未指定 已经分配了。您可能需要为 检查器中的EnemyAI脚本 我对所有这些脚本编写的东西都有点陌生,我试着查看其他论坛,但它们没有任何帮助,但让我更加困惑。以下是脚本: using UnityEngine; using System.Collections; public class EnemyAI : MonoBehaviour { public Transform pla
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform player;
public float playerDistance;
public float rotationDamping;
public float moveSpeed;
//Use this for initialization
void Start () {
}
//Update is called once per frame
void Update () {
playerDistance = Vector3.Distance (player.position, transform.position);
if (playerDistance < 15f) {
lookAtPlayer ();
}
if (playerDistance < 12f) {
chase ();
}
}
void lookAtPlayer()
{
Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * rotationDamping);
}
void chase()
{
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
}
有什么想法吗?您的变量播放器是Transform类型,用于
Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
在为其指定任何值之前。我相信Transform是您项目中的另一个类,而player就是这种类型的对象。您可能希望在尝试使用该对象之前实例化该对象
差不多
player = new Transform(...);
在C语言中,诸如EnemyAI引用之类的引用可以设置为Null,这意味着它们不指向任何地方。当您的代码试图在空引用上运行某些方法时,这会导致很多错误 我怀疑Unity创造了一种特殊的机制来防止这种错误发生在你身上。Unity的MonoBehavior的公共字段用于在游戏运行之前在编辑器中设置MonoBehavior的实例。单行为通常不是从头创建的,99%的情况下,它们是从编辑器中编辑和保存的实例反序列化的 因此,有了这个错误,Unity警告您没有为MonoBehavior的这个特定实例赋值。若要修复此问题,请打开编辑器,选择此错误通常引用的对象,您只需单击控制台中的错误,对象将被选中,将引用设置为某个对象,错误将被修复
然而,从脚本的上下文判断,您可以选择不同的路径。很可能你在场景中只有一个玩家,同时你可能有数百个敌人-你不想将他们的引用分配给玩家上百次!如果你想使用预制件,你甚至不能。因此,与其将其设置为公共字段,不如将其设置为私有字段,并在初始化时使用Start方法将其分配给该字段。FindGameObjectWithTagPlayer是一种可能的方法;然而,根据我的经验,在强大的静态类型语言(如C)中,依赖标记和字符串通常是次优的,我会使用或模式来查找播放器。不应使用构造函数创建Unity组件,一个变换组件总是在创建时自动添加到游戏对象中,并且不能添加。