【发布时间】:2021-01-02 04:45:16
【问题描述】:
我正在制作 FPS 游戏,我正在尝试一些枪支脚本,但 Unity 一直显示错误 CS0120,但问题是我没有使用任何“静态”或需要它的东西,至少我认为我没用。
主要代码:
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
healthPoints hp = hit.transform.GetComponent<healthPoints>();
if(hp != null)
{
//Here is where I get the error
healthPoints.TakeDamage(damage);
}
}
}
}
HP 代码:
public class healthPoints : MonoBehaviour
{
public float health = 100f;
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
}
“错误 CS0120 非静态字段、方法或属性‘healthPoints.TakeDamage(float)’需要对象引用”
【问题讨论】:
-
你有一个名为
hp的实例,但你在类而不是实例上调用healthPoints.TakeDamage() -
错误告诉你需要做什么;由于
TakeDamage方法不是static,您需要使用对healthPoints类的引用才能调用它(您在hp中拥有)。
标签: c# unity3d raycasting