0

正如标题所说。我得到一个 NullReferenceException 瞬间,然后,一切正常。谁能告诉我为什么会这样?

这是我的代码,错误来自第 43 行:

    #pragma strict
//NOTE: Display the health of the enemy that is targetted by the player!

//private var enemyGO : GameObject;
//private var enemyScript : EnemyAI;

var healthText : GUIText;


var myPlayer : Transform;
var myPlayerScript : PlayerScript;

var myPlayerTarget : Transform;
var myPlayerTargetScript : EnemyAI;


function Start () {
    myPlayer = GameObject.FindGameObjectWithTag("Player").transform;
    myPlayerScript = myPlayer.GetComponent("PlayerScript");

/*  if (myPlayerScript.target != null) {
        myPlayerTarget = myPlayerScript.target;

        myPlayerTarget.GetComponent("EnemyAI");
    }*/

//  enemyGO = GameObject.Find("Enemy");
//  enemyScript = enemyGO.GetComponent("EnemyAI");
}


function FixedUpdate () {
    if (myPlayerScript.target != null) {
        myPlayerTarget = myPlayerScript.target;

        myPlayerTargetScript = myPlayerTarget.GetComponent("EnemyAI");
    }
}


function OnGUI () {
    if (myPlayerScript.target != null) {
        GUI.Label (Rect (((Screen.width / 2) + Screen.width / 3), 16, 250, 20), "EnemyHP: " + (Mathf.Round(myPlayerTargetScript.curHealth)) + " / " + /*(Mathf.Round(*/myPlayerTargetScript.maxHealth/*))*/);
    }
}

谢谢 :)

编辑:这不显示行:P 所以错误发生在我的 OnGUI 函数中的 GUI.Label... 行中:)

4

1 回答 1

0

由于您已经在 myPlayerTargetScript 中保存了对 EnemyAI 脚本的引用,因此您应该在 OnGUI 中检查它是否为 null

也不要将 FixedUpdate 用于此类事情。FixedUpdate 属于物理系统。只需使用更新:

 #pragma strict

var healthText : GUIText;

var myPlayer : Transform;
var myPlayerScript : PlayerScript;

var myPlayerTarget : Transform;
var myPlayerTargetScript : EnemyAI;


function Start () {
    myPlayer = GameObject.FindGameObjectWithTag("Player").transform;
    myPlayerScript = myPlayer.GetComponent(PlayerScript);
}

function Update () {
    if (myPlayerScript.target != null) {
        myPlayerTarget = myPlayerScript.target;

        myPlayerTargetScript = myPlayerTarget.GetComponent(EnemyAI);
    }
}

function OnGUI () {
    if (myPlayerTargetScript  != null) {
        GUI.Label (Rect (((Screen.width / 2) + Screen.width / 3), 16, 250, 20), "EnemyHP: " + (Mathf.Round(myPlayerTargetScript.curHealth)) + " / " + myPlayerTargetScript.maxHealth);
    }
}

ps:你应该在发布之前整理你的脚本;)

于 2013-08-30T00:49:45.677 回答