《unity手机游戏开发》4.7敌人Object reference not set to an instance of an object

本文介绍了解决Unity游戏开发中Object reference not set to an instance of an object错误的方法。通过为变量myCurrentPathNode正确赋值,确保游戏对象能够顺利跟随路径节点移动。

通过这本书学习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));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值