【问题标题】:2D Instantiated object stops moving when used with timer与计时器一起使用时,2D 实例化对象停止移动
【发布时间】:2021-12-02 22:17:49
【问题描述】:

您好,我正在尝试创建一个实例化和对象的系统,并将其移动到一组航点。当我在 Start() 函数中使用 intantiate 时,它​​会像预期的那样通过航路点,但是当我将实例化线添加到我的 update() 函数时,它只会移动一会儿然后停止,其余的实例化也是如此对象。我猜它与计时器有关,但我尝试了一些方法,但它们都导致相同的事情。希望有人能帮忙。

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

public class waypointTest : MonoBehaviour
{
[SerializeField] private Transform[] waypoints;

public GameObject waypointInvader;
GameObject go;        
private int nextUpdate = 1;
public float speed = 5f;
private int waypointIndex;




void Start()
{               
    
}
void Update()
{
    if (Time.time >= nextUpdate)
    {
        nextUpdate = Mathf.FloorToInt(Time.time) + 1;
        go = Instantiate(waypointInvader, transform.position, transform.rotation) as GameObject;            
    }        

    
    if (go.transform.position != waypoints[waypointIndex].transform.position)
    {
        Vector3 newPos = Vector3.MoveTowards(go.transform.position, waypoints[waypointIndex].transform.position, speed * Time.deltaTime);
        go.transform.position = newPos;
        if (newPos == waypoints[waypointIndex].transform.position)
        {
            waypointIndex += 1;
        }
        if (waypointIndex == waypoints.Length)
        {
            waypointIndex = 0;
        }
    }
    
}
}

【问题讨论】:

    标签: unity3d timer instantiation


    【解决方案1】:

    问题是您丢失了对要移动的对象的引用。

    如果实例化在Start()内:

    1. go 设置为实例化对象
    2. go 被移动到每个航路点
    3. go 被移动到第一个航路点
    4. go 再次通过航路点

    如果实例化在Update() 内:

    1. go 设置为第一个实例化对象
    2. go 被移动到几个航路点直到 Time.time >= nextUpdate 返回真
    3. go 设置为 second 实例化对象,并将失去对 first go 的引用
    4. 第一个go停止移动
    5. go开始移动
    6. 重复

    解决这个问题的一种方法是给移动对象go自己的移动脚本。这样你只需要实例化go,它就会自己处理它的移动。如果go 不知道航点在哪里,您可以在实例化后将其提供给它(例如waypointInvader 是一个预制件)。例如:

    if (Time.time >= nextUpdate)
    {
        nextUpdate = Mathf.FloorToInt(Time.time) + 1;
        go = Instantiate(waypointInvader, transform.position, transform.rotation) as GameObject;
        go.GetComponent<GoMovement>().ListOfWaypoints = waypoints;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2017-02-14
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多