OnGUI вызывается только в первом компоненте
Я создаю игру, чтобы узнать о Unity, просматривая учебник ( этот), и у моего Player есть два компонента: PlayerHealth и PlayerAttack. Оба хорошо работают, но проблема в том, что когда я пытался что-то сделать в OnGUI второго компонента (PlayerAttack), OnGUI в PlayerAttack никогда не вызывался.
Это потому, что 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);
}
}
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);
}
}
}
1 ответ
Решение
Ваш метод OnGUI в классе PlayerAttack имеет тип "onGUI", а не "OnGUI" (заглавная O). Помните, что C# чувствителен к регистру.