繁体   English   中英

为什么 unity3d 克隆没有被销毁

[英]why are unity3d clones not destroyed

在这段代码中,我在对象接近玩家原点时克隆它们,并在它们经过它时销毁它们。

此脚本附加到两个游戏对象。

游戏进行时,原来的两个object被破坏时从层次结构中消失。 当克隆体被摧毁时,它们会从游戏画面中消失,但仍保留在层级中。

我认为这是一个问题。 我该如何解决?

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

public class MoveTraffic : MonoBehaviour
{
    
    private float vehicleSpeed = 8.0f;
    private Vector3 startPosition;
    private bool needsDuplicate = true;
    // Start is called before the first frame update
    void Start()
    {
        startPosition = transform.position;
        // force startPosition Z to be at the edge of the road;
        startPosition.z = 178.0f;
    }

    // Update is called once per frame
    void Update()
    {
        // Move the vehicle forward or backward
        transform.Translate(Vector3.forward * Time.deltaTime * vehicleSpeed);

        //create duplicates at certain points along the road, starting them back at startPosition.
        var pz = transform.position.z;
        if (needsDuplicate)
        {
            //if ((pz < 178f * .75 && pz > 178f * .7) || (pz < 178 * .5 && pz > 178f* .4))
            if (pz < 178 * .5 && pz > 178f * .4)
            {
                Instantiate(this, startPosition, transform.rotation);
                needsDuplicate = false;
            }
        }
        else
        {
            //if ((pz < 178f * .7 && pz > 178f * .6) || (pz < 178 * .5 && pz > 178f * .6))
            if (pz < 178 * .5 && pz > 178f * .6)
            {
                needsDuplicate = true;
            }
        }
            
        //Respawn and destroy when it gets to the end of the road.
        if (transform.position.z < -2)
        {
            //transform.position = new Vector3(transform.position.x, transform.position.y, restartZ);
            Instantiate(this, startPosition, transform.rotation);
            Destroy(this.gameObject);
        }
    }
}

问题不在于克隆没有被摧毁。 您实例化的每个克隆都在创建自身的副本(可能重叠),给人一种它从场景中消失而不是从层次结构中消失的错觉。 如果你双击任何一个应该没有被破坏的克隆体,你将在场景模式中看到该克隆体的确切位置。

在我看来,如果场景中只需要两辆车,则不必在每次销毁它时都克隆变换。

//Respawn and destroy when it gets to the end of the road.
if (transform.position.z < -2)
{
  Destroy(this.gameObject);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM