Unity中的Update()表现得很奇怪

时间:2017-03-05 17:10:47

标签: c# unity3d

我在Unity中有多个预制件实例。每个实例都有此Update():

void Update()
{
    Vector3 retning1200 = new Vector3(0, 0, 1);
    Vector3 retning0130 = new Vector3(1, 0, 1);

    Debug.DrawRay(transform.position, retning1200, Color.green, 1);
    Debug.DrawRay(transform.position, retning0130, Color.green, 1);


    if (Physics.Raycast(transform.position, retning1200, 1))
    {
        antalNaboer++;
    }

    if (Physics.Raycast(transform.position, retning0130, 1))
    {
        antalNaboer++;
    }

    Debug.Log("Myre i position: " + transform.position.x + " " + transform.position.y);
    Debug.Log("antal naboer :" + antalNaboer.ToString());

    antalNaboer = 0;
}  

我希望Update()内的代码在每一帧中运行一次。但似乎有时并非所有实例都会运行。有时在一帧中多次。结果(antal myrer)不一样。

Myre i position:-1 0 antal naboer:2

Myre i position:-1 0 antal naboer:1

Myre i position:1 0 antal naboer:2

1 个答案:

答案 0 :(得分:3)

应该在FixedUpdate方法中检查任何类型的物理计算。 顾名思义,此方法将在固定的持续时间内调用,因此两个连续调用之间的持续时间始终相同,而不像Update方法,这可能会因FPS而异。

void FixedUpdate()
{
    Vector3 retning1200 = new Vector3(0, 0, 1);
    Vector3 retning0130 = new Vector3(1, 0, 1);

    Debug.DrawRay(transform.position, retning1200, Color.green, 1);
    Debug.DrawRay(transform.position, retning0130, Color.green, 1);


    if (Physics.Raycast(transform.position, retning1200, 1))
    {
        antalNaboer++;
    }

    if (Physics.Raycast(transform.position, retning0130, 1))
    {
        antalNaboer++;
    }

    Debug.Log("Myre i position: " + transform.position.x + " " + transform.position.y);
    Debug.Log("antal naboer :" + antalNaboer.ToString());

    antalNaboer = 0;
}  

有关两者之间差异的更多信息,请查看此链接 http://answers.unity3d.com/questions/10993/whats-the-difference-between-update-and-fixedupdat.html