C# 我不明白为什么addForce不在fixedUpdate中工作。不过,它只是在正常更新中工作
这是我的密码 它应该使敌人向后移动,当它击中对撞机时,它会摧毁它,并在分数上加一分C# 我不明白为什么addForce不在fixedUpdate中工作。不过,它只是在正常更新中工作,c#,unity3d,C#,Unity3d,这是我的密码 它应该使敌人向后移动,当它击中对撞机时,它会摧毁它,并在分数上加一分 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class forward : MonoBehaviour { float score; public Text text; private void FixedUpdat
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。另外,我认为你不应该在FixeUpdate前有私人信息。这可能就是问题所在。应该是这样的
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;
}
}
}
这是什么意思。我是说这个。可能是多余的,但如果删除它,则基本相同。通常,你会说gameobject.GetComponent,因此你可以将游戏对象指定为这个,这就是这个脚本所附加的游戏对象。我同意Caleb Sadler关于在更新中不使用GetComponent的观点,这可能仍然是一个昂贵的操作。但这个答案不会解决你的问题,至少我很确定。将私有void FixedUpdate转换为void FixedUpdate会有帮助吗?@CalebSadler不!这完全没有区别。在c语言中没有特定的可访问性,默认情况下类中的所有内容都是私有的。您可以将这些消息方法设置为私有、公共或受保护。。打印出来的allIs测试没有什么区别吗?如果没有,则根本不会调用FixeUpdate。只是一个无关的旁注:有趣的是,一个名为forward的类不断地添加一个指向后的力^^