[英]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.