Ria*_*ter -1 c# unity-game-engine visual-studio
我目前正在 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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在敌人的脚本文件中使用上述方法时,出现错误,指出“Assets/Custom Scripts/BeetleScript.cs(46,28): error 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");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何解决此问题的帮助将不胜感激。
小智 5
你的方法是private. 你必须写public在你想从类外部访问的方法前面。
public void ReduceHealth()
{
...
}
Run Code Online (Sandbox Code Playgroud)