"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);
}
}