c# - 我不知道为什么 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;
}
}
}
解决方案
我不知道为什么会发生这种情况,但不应在更新中调用 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;
}
}
}
推荐阅读
- python - 为 pandas 数据框中的两列组合按顺序独立分配唯一 ID
- azure-active-directory - 更改密码后 Powershell 中的身份验证问题
- linux - 生产空间几乎用完 - 如何从容器中清除日志?
- laravel - 如何安全地存储客户的 API 密钥?
- javascript - 如何将值传递给 useState
- typescript - Typescript 有没有办法警告将对象分配到另一个对象作为参考分配
- java - 在 openLiberty 中提供静态文件
- node.js - 如何更新nodejs版本
- internet-explorer-11 - IE11浏览器清除浏览历史后网站加载缓慢或不加载
- java - 写入文本文件而不覆盖现有内容