由于其保护级别,方法无法访问

时间:2013-07-01 15:26:03

标签: c# unity3d

我正在使用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()”抛出错误 -
“由于其保护级别,方法无法访问”

我需要帮助...

1 个答案:

答案 0 :(得分:5)

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

访问它
  

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

外部访问专用嵌套类型

将定义更改为

public void HealthRulse(int adj)