Unity 2019.2.4f1 中的"An object reference is required for the non-static field, method, or property"


当我运行代码时,Unity抛出了这个编译器错误

"Assets\Stealth.cs(25,13(:error CS0120:对象引用非静态字段、方法或属性所必需的"RaycastHit2D.collider'">

我尝试过以多种不同的方式声明RaycastHit2D变量,但都抛出了不同的错误。

public float rotationSpeed;
public float distance;
private void Start()
{
Physics2D.queriesStartInColliders = false;
}

void Update()
{
transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
if(RaycastHit2D.collider.CompareTag("Player")){
Destroy(RaycastHit2D.collider.gameObject);
}
RaycastHit2D RaycastHit = Physics2D.Raycast(transform.position, transform.right, distance);
if (RaycastHit2D.collider != null){
Debug.DrawLine(transform.position, RaycastHit2D.point, Color.red);
} else {
Debug.DrawLine(transform.position, transform.position + transform.right * distance, Color.green);
}
}

}

当光线与玩家的2D对撞机接触时,它应该会导致场景中的gameObject破坏玩家,但这并没有发生。

编译器错误CS0120表示您正试图访问实例成员,就好像它是静态成员一样。

RaycastHit2D是类名,因此表达式RaycastHit2D.collider正试图访问名为collider的静态成员。但是,collider是实例属性,因此需要RaycastHit2D实例

您的变量RaycastHit包含此类的一个实例,因此您可能打算改为编写RaycastHit.collider,如下所示:

void Update()
{
transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
RaycastHit2D RaycastHit = Physics2D.Raycast(transform.position, transform.right, distance);
if (RaycastHit.collider != null){
// This had to be moved below where RaycastHit is assigned,
// and after verifying that collider is not null
if(RaycastHit.collider.CompareTag("Player")){
Destroy(RaycastHit.collider.gameObject);
}
Debug.DrawLine(transform.position, RaycastHit.point, Color.red);
} else {
Debug.DrawLine(transform.position, transform.position + transform.right * distance, Color.green);
}
}

相关内容

  • 没有找到相关文章

最新更新