我是团结的新手,我正在关注这个tutorial here,我发现了GetComponent<Rigidbody2D>
部分,但我仍然得到A Field Initializer cannot reference the nonstatic field, method, or property. UnityEngine.Component.GetComponent<Rigidbody2D>()
我不明白如何修复它,没有其他地方有帮助。我在Unity论坛上发帖,但尚未收到答案。
这是代码。谢谢你的帮助!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerSCRIPT : MonoBehaviour {
public float maxSpeed = 10f;
bool faceRight = true;
Animator anim;
// Use this for initialization
void Start ()
{
//...
}
// Update is called once per frame
void FixedUpdate ()
{
float move = Input.GetAxis("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (move < 0 && !faceRight)
Flip();
else if (move < 0 && faceRight)
Flip();
}
void Flip()
{
faceRight = !faceRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
答案 0 :(得分:0)
尝试以下,
private Rigidbody2D body;
void Start
{
body = GetComponent<Rigidbody2D>();
}
在FixedUpdate()中使用以下,
body.velocity = new Vector2(move * maxSpeed, body.velocity.y);