问题描述
我正在制作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()
:
if(hp != null)
{
// Here is where I get the error
hp.TakeDamage(damage);
}
只能访问类的静态方法,而无需先实例化该类的对象。