0

我正在使用 Unity3d 和 C#,并且我有两个脚本:

脚本1:

using UnityEngine;
using System.Collections;

public class PlayerAttack : MonoBehaviour {

    public GameObject target;

    // Update is called once per frame
    void Update () {

        if(Input.GetKeyUp(KeyCode.F))
        {
            Attack();
        }
    }
     void Attack() {
        EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
        eh.HealthRulse(-10);
    }

}

脚本 2:

using UnityEngine;
using System.Collections;

public class EnemyHealth : MonoBehaviour {
public int curHealth = 100;
public int maxHealth = 100;
public float healthBarLeangth;
    // Use this for initialization
    void Start () {
    healthBarLeangth = Screen.width / 2;
    }

    // Update is called once per frame
    void Update () {
         HealthRulse(0);
    }
    void OnGUI() {
        GUI.Box(new Rect(10,40,Screen.width / 2 / (maxHealth / curHealth),20),curHealth + "/" + maxHealth);
    }
    void HealthRulse(int adj){
        if ( curHealth < 0)
            curHealth = 0;
        if (curHealth > maxHealth)
            curHealth = maxHealth;
        if(maxHealth < 1)
            maxHealth = 1;

        curHealth += adj;
        healthBarLeangth = (Screen.width / 2) * (curHealth / (float)maxHealth);
    }
}

在“脚本 2”中定义并由 GetComponent 在“脚本 1”中调用的函数“HeathRulse()”引发错误-
“方法由于其保护级别而无法访问”

我需要帮助...

4

1 回答 1

5

由于您没有定义任何访问修饰符,因此方法HealthRulse是私有的,因此您无法从外部EnemyHealth类访问它

默认情况下,类成员和结构成员(包括嵌套类和结构)的访问级别是私有的。不能从包含类型外部访问私有嵌套类型

将定义更改为

public void HealthRulse(int adj)
于 2013-07-01T15:29:03.343 回答