2

我正在创建一个游戏来了解 Unity 观看教程(这个),我的 Player 有两个组件:PlayerHealth 和 PlayerAttack。两者都工作正常,但问题是当我试图在第二个组件(PlayerAttack)的 OnGUI 中做某事时,PlayerAttack 中的 OnGUI 永远不会被调用。

是因为 PlayerAttack 添加在 PlayerHealth 下面吗?按照下面的代码和一些打印。

组件订购。

PlayerHealth.cs

using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour {
    public int maxHealth = 100;
    public int curHealth = 100;

    public float healthBarLenght;

    // Use this for initialization
    void Start () {
        healthBarLenght = Screen.width / 3;
    }

    // Update is called once per frame
    void Update () {
        AddjustCurrentHealth(0);
    }

    void OnGUI(){
        GUI.Box(new Rect(10, 10, healthBarLenght, 20), curHealth + "/" + maxHealth);
    }

    public void AddjustCurrentHealth(int adj){
        curHealth += adj;

        curHealth = Mathf.Min(Mathf.Max(curHealth, 0), maxHealth);
        maxHealth = Mathf.Max(maxHealth, 1);

        healthBarLenght = ((float) Screen.width / 3) * (curHealth / (float) maxHealth);
    }
}

玩家攻击.cs

using UnityEngine;
using System.Collections;

public class PlayerAttack : MonoBehaviour {
    public GameObject target;
    public float attackTimer;
    public float coolDown;

    // Use this for initialization
    void Start () {
        attackTimer = 0;
        coolDown = 2;
    }

    // Update is called once per frame
    void Update () {
        if(attackTimer > 0){
            attackTimer -= Time.deltaTime;
        } else {
            attackTimer = 0;
        }

        if(Input.GetKeyUp(KeyCode.F) && attackTimer == 0){
            attackTimer = coolDown;

            Attack();
        }
    }

    void onGUI(){
        float loadPct = coolDown - attackTimer;

        GUI.Box(new Rect(10, 30, loadPct, 10), loadPct + "%");
    }

    private void Attack(){
        float distance = Vector3.Distance(target.transform.position, transform.position);
        Vector3 dir = (target.transform.position - transform.position).normalized;
        float direction = Vector3.Dot(dir, transform.forward);

        Debug.Log(direction);

        if(distance <= 2.5 && direction > 0.9)
        {
            EnemyHealth eh = (EnemyHealth) target.GetComponent("EnemyHealth");

            eh.AddjustCurrentHealth(-1);
        }
    }
}
4

1 回答 1

5

您在 PlayerAttack 类上的 OnGUI 方法键入“onGUI”,而不是“OnGUI”(大写 O)。请记住 C# 区分大小写。

于 2014-05-03T18:20:46.113 回答