简体   繁体   English

从列表中删除或删除生成对象

[英]Remove or Delete spawning objects from the List

I made a script that spawning unlimited moving objects with LIST from positions .I want to delete the objects that collides for example with boundary.I tried to delete them applying destroy script to the object , but the console output was ..."has been destroyed but you are still trying to access it" or "use DestroyImmediate".How to destroy them?Any suggestions? 我制作了一个脚本,该脚本从位置产生带有LIST的无限移动对象。我想删除与边界碰撞的对象。我试图通过对对象应用destroy脚本来删除它们,但是控制台输出是...”已销毁,但您仍在尝试访问它”或“立即使用DestroyImmediate”。如何销毁它们?有什么建议吗?

Spawning Code: 生成代码:

public  List<GameObject> respawn = new List<GameObject> ();
public Vector3[] positions=new Vector3[5];  
public GameObject barrier;
public BarrierMoving barrierMoving;
public bool isMoving=true;
public int lastRandom = 0;

float speed=60f;

void Start ()
{
    barrierMoving = GameObject.FindObjectOfType<BarrierMoving> ();
    InvokeRepeating ("SpawnBarrier",1f,speed*Time.deltaTime);
}

public void Update ()
{
    if(isMoving)
    {
        foreach(GameObject stop in respawn)
        {
            stop.transform.Translate (0f,0f,-0.4f);
        }
    }
}

// Spawning Function
void SpawnBarrier()
{
    for(int i=0;i<=5;i++)
    {
        respawn.Add (Instantiate (barrier, positions [i], Quaternion.identity)as GameObject);
    }
}

Destroy Script: 销毁脚本:

RespawnBarriers respawnBarriers;

void Start ()
{
    respawnBarriers = GameObject.FindObjectOfType<RespawnBarriers> ();
}

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.CompareTag("Destroy"))
    {
        Destroy (respawnBarriers.barrier);
    }
}

You reference your list in the update method of your spawning code. 您可以在生成代码的update方法中引用列表。 When you destroy your object in your destroy script, the reference of it in your respawn list is lost and generates your error. 当您在销毁脚本中销毁对象时,其在重生列表中的引用将丢失并产生错误。

You should remove the reference from the respawn list before destroying the object. 在销毁对象之前,应从重生列表中删除引用。 I would recommend making a static reference to your spawn script for easy access, if you only have one instance of it. 如果您只有一个实例,我建议您对它的生成脚本进行静态引用以便于访问。

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

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