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

时间:2018-10-19 10:26:34

标签: c# visual-studio unity3d

我目前正在Unity 2018中进行开发,并编写了一个脚本来减少与敌人碰撞时角色的生命值:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthManager : MonoBehaviour
{

    public static int currentHealth;
    public Slider healthBar;

    void Awake()
    {
        healthBar = GetComponent<Slider> ();
        currentHealth = 100;
    }

    void ReduceHealth()
    {
        currentHealth = currentHealth - 1;
        healthBar.value = currentHealth;
    }

    void Update()
    {
        healthBar.value = currentHealth;
    }
}

当我尝试在脚本文件中使用针对敌人的方法时,出现错误,指出“资产/自定义脚本/BeetleScript.cs(46,28):错误CS0122:“ HealthManager.ReduceHealth()”不可访问达到其保护水平”

以下是敌人脚本,该脚本初始化正在使用的变量并调用该方法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BeetleScript : MonoBehaviour
{

Animator animator;
public GameObject cucumberToDestroy;
public bool cherryHit = false;
public float smoothTime = 3.0f;
public Vector3 smoothVelocity = Vector3.zero;
public PointsManager _ptsManager;
public HealthManager _healthManager;

void Start()
{
    animator = GetComponent<Animator>();
}

void Update()
{
    if (cherryHit)
    {

        var cm = GameObject.Find("CucumberMan");
        var tf = cm.transform;
        this.gameObject.transform.LookAt(tf);

        // move towards Cucumber Man
        animator.Play("Standing Run");

        transform.position = Vector3.SmoothDamp(transform.position, tf.position,
            ref smoothVelocity, smoothTime);
    }
}

// Collision Detection Test
void OnCollisionEnter(Collision col)
{
    if (col.gameObject.CompareTag("Player"))
    {

        _healthManager = GameObject.Find
        ("Health_Slider").GetComponent<HealthManager>();
        _healthManager.ReduceHealth();

        if (!cherryHit)
        {

            BeetlePatrol.isAttacking = true;

            var cm = GameObject.Find("CucumberMan");
            var tf = cm.transform;
            this.gameObject.transform.LookAt(tf);

            animator.Play("Attacking on Ground");
            StartCoroutine("DestroySelfOnGround");
        }
        else
        {
            animator.Play("Standing Attack");
            StartCoroutine("DestroySelfStanding");
        }
    }  

 }
}

任何帮助解决此问题的方法将不胜感激。

2 个答案:

答案 0 :(得分:3)

您的方法是private。 您必须在要从类外部访问的方法前面编写public

public void ReduceHealth()
{
...
}

答案 1 :(得分:0)

您需要将void ReduceHealth()设为公开-> public void ReduceHealth()

相关问题