C# OnGUI仅在第一个组件中调用
我正在创建一个游戏来学习Unity观看教程(),我的玩家有两个组件:PlayerHealth和PlayerTack。两者都工作得很好,但问题是当我试图在第二个组件(PlayerAttack)的OnGUI中做一些事情时,PlayerAttack中的OnGUI从未被调用 是因为PlayerHealth下面添加了PlayerTack?按照下面的代码和一些打印 PlayerHealth.csC# OnGUI仅在第一个组件中调用,c#,unity3d,unity-components,C#,Unity3d,Unity Components,我正在创建一个游戏来学习Unity观看教程(),我的玩家有两个组件:PlayerHealth和PlayerTack。两者都工作得很好,但问题是当我试图在第二个组件(PlayerAttack)的OnGUI中做一些事情时,PlayerAttack中的OnGUI从未被调用 是因为PlayerHealth下面添加了PlayerTack?按照下面的代码和一些打印 PlayerHealth.cs using UnityEngine; using System.Collections; public cl
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);
}
}
playeratack.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);
}
}
}
使用UnityEngine;
使用系统集合;
公共类剧目:单一行为{
公共游戏对象目标;
公共浮动攻击计时器;
公共浮子冷却;
//用于初始化
无效开始(){
攻击计时器=0;
冷却时间=2;
}
//每帧调用一次更新
无效更新(){
如果(攻击计时器>0){
attackTimer-=Time.deltaTime;
}否则{
攻击计时器=0;
}
if(Input.GetKeyUp(KeyCode.F)&&attackTimer==0){
攻击计时器=冷却时间;
攻击();
}
}
void onGUI(){
浮动负载PCT=冷却-攻击计时器;
Box(新的Rect(10,30,loadPct,10),loadPct+“%”;
}
私有无效攻击(){
浮动距离=矢量3.距离(target.transform.position,transform.position);
Vector3 dir=(target.transform.position-transform.position).normalized;
浮点方向=矢量3.Dot(dir,transform.forward);
Debug.Log(方向);
如果(距离0.9)
{
EnemyHealth eh=(EnemyHealth)target.GetComponent(“EnemyHealth”);
eh.AddjustCurrentHealth(-1);
}
}
}
您在PlayerAttack类上的OnGUI方法键入的是“OnGUI”,而不是“OnGUI”(大写字母O)。记住C#区分大小写