首页 > 解决方案 > 我不知道为什么 addForce 在fixedUpdate 中不起作用。虽然它在正常更新中工作

问题描述

这是我的代码,它应该让敌人向后移动,当它撞到盒子对撞机时,它会摧毁它并在分数上加一分。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class forward : MonoBehaviour
{
    float score;
    public Text text;

    private void FixedUpdate()
    {
        GetComponent<Rigidbody>().AddForce(Vector3.back * 5);
        text.text = "score: " + score;
        print("test");
    }
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.tag == "Finish")
        {
           Destroy(gameObject);
            score = score =+ 1;
        }
    }


}

标签: c#unity3d

解决方案


我不知道为什么会发生这种情况,但不应在更新中调用 GetComponent。另外,我认为您不应该在 FixedUpdate 之前使用 private。这可能是问题所在。它应该看起来像这样。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class forward : MonoBehaviour
{
    float score;
    public Text text;
    private Rigidbody rb;

    void Start(){
        rb = this.GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rb.AddForce(Vector3.back * 5);
        text.text = "score: " + score;
        print("test");
    }
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.tag == "Finish")
        {
           Destroy(gameObject);
            score = score =+ 1;
        }
    }


}

推荐阅读