我的播放器没有死,并且控制台给我的错误是:
NullReferenceException:对象引用未设置为的实例 对象Movement.OnCollisionEnter2D(UnityEngine.Collision2D碰撞) (在Assets / Scripts / Movement.cs:74。
我的位置已经有了标签,但是游戏仍然给了我这个标签。地面也有对撞机+刚体2d
public class Movement : MonoBehaviour
{
public float moveSpeed = 300;
public GameObject character;
private Rigidbody2D characterBody;
private float ScreenWidth;
private Rigidbody2D rb2d;
private Score gm;
public bool isDead = false;
public Vector2 jumpHeight;
void Start()
{
ScreenWidth = Screen.width;
characterBody = character.GetComponent<Rigidbody2D>();
gm = GameObject.FindGameObjectWithTag("gameMaster").GetComponent<Score>();
}
// Update is called once per frame
void Update()
{
if (isDead) { return; }
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) //makes player jump
{
GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
}
int i = 0;
while (i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2)
{
RunCharacter(1.0f);
}
if (Input.GetTouch(i).position.x < ScreenWidth / 2)
{
RunCharacter(-1.0f);
}
++i;
}
}
void FixedUpdate()
{
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
}
private void RunCharacter(float horizontalInput)
{
characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ground")) // this will return true if the collision gameobject has ground tag on it.
{
isDead = true;
rb2d.velocity = Vector2.zero;
GameController.Instance.Die();
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("coin"))
{
Destroy(col.gameObject);
gm.score += 1;
}
}
}
答案 0 :(得分:0)
正如BugFinder所说,您从未说过哪一行是74行。 我可以看到的一件事是,您永远不会为rb2d设置值。 在您的Start()方法中,您可以添加:
rb2d = GetComponent<Rigidbody2D>();
这应该可以解决该问题。如果还有其他任何内容,请评论并说出第74行。 :)