我正在创建一个游戏,以了解Unity观看教程(this one)的过程,并且我的播放器具有两个组件: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);
}
}
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);
}
}
}
最佳答案
您在PlayerAttack类上的OnGUI方法键入“ onGUI”,而不是“ OnGUI”(大写O)。请记住,C#区分大小写。
关于c# - OnGUI仅在第一个组件中被调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23448040/