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

本文关键字:访问 于其 保护 方法 | 更新日期: 2023-09-27 18:20:31

我使用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);
    }
}

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

我需要帮助。。。

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

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

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

将定义更改为

public void HealthRulse(int adj)