通过这本书学习unity发现Object reference not set to an instance of an object这个问题
通过谷歌大法了解到是未实例化的问题,仔细检查了代码,发现书籍给的代码中myCurrentPathNode未赋值
所以在enemy.cs中加了如下代码
private void Awake()
{
myCurrentPathNode = GameObject.FindGameObjectWithTag("pathnode").GetComponent<PathNode>();
}
这是修正后enemy.cs的完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour {
public PathNode myCurrentPathNode;
public int myLife = 15;//生命
public int maxMyLife = 15;
public float myspeed = 2;
//敌人的类型
public enum TYPE_ID
{
GRCUND,
AIR,
}
public TYPE_ID myType = TYPE_ID.GRCUND;
private void Awake()//这个是关键
{
myCurrentPathNode = GameObject.FindGameObjectWithTag("pathnode").GetComponent<PathNode>();
}
private void Update()
{
RotateTo();
MoveTo();
}
//转向下一个路点
public void RotateTo()
{
float current = transform.eulerAngles.y;
transform.LookAt(myCurrentPathNode.transform);
Vector3 target = transform.eulerAngles;
float next = Mathf.MoveTowardsAngle(current, target.y, 120 * Time.deltaTime);
transform.eulerAngles =new Vector3(0, next, 0);
}
//向下一个路口移动
public void MoveTo()
{
Vector3 thisPosition = transform.position; ;
Vector3 currentPathNodePosition = myCurrentPathNode.transform.position;
//距离子路点的距离
float distance = Vector3.Distance(new Vector2(thisPosition.x, thisPosition.z), new Vector2(currentPathNodePosition.x, currentPathNodePosition.z));
if(distance<1.0)
{
if(myCurrentPathNode.childPathNode==null)
{
GameManager.instance.setDamage(1);
Destroy(this.gameObject);
}
else
{
myCurrentPathNode = myCurrentPathNode.childPathNode;
}
}
transform.Translate(new Vector3(0, 0, myspeed * Time.deltaTime));
}
}