Search code examples
c#unity-game-engineunity-components

OnGUI is called just in first component


I'm creating a game to learn about Unity watching a tutorial (this one) and my Player has two components: PlayerHealth and PlayerAttack. The both are working fine as well but the problem is when I tried to do something in a OnGUI of second component (PlayerAttack), the OnGUI in PlayerAttack is never called.

Is because PlayerAttack is added below PlayerHealth? Follow below the codes e some prints.

Components order.

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);
    }
}

PlayerAttack.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);
        }
    }
}

Solution

  • Your OnGUI method on PlayerAttack class is typed "onGUI", not "OnGUI" (capital O). Remember C# is case-sensitive.