从脚本Unity3d C#中销毁由脚本创建的对象

本文关键字:脚本 创建 对象 Unity3d | 更新日期: 2023-09-27 18:07:47

向下运行好吧,伙计们和女孩们需要一点帮助。基本上,我是从打开位置的预制件实例化healthPack。经过一段时间后,如果HealthPack没有被提取,我将尝试销毁它,将bool healthPackExist设置回false,并在空闲位置实例化另一个HealthPack。

问题:当我试图访问正在实例化的gameObject时,我最终要么破坏整个父层次结构,要么只是删除脚本。

解决方案我尝试过破坏根对象,搜索创建的对象的名称,向对象添加标记(健康包(,搜索它总是出错。

代码如下:

public GameObject healthPackPrefab;
public GameObject health;
private float healthTimer;
private bool healthExist;
// Use this for initialization
void Start () 
{
    //set healthExist to false to indicate no health packs exist on game start
    healthExist = false;
}
// Update is called once per frame
void Update () 
{
    //first check to see if a health pack exist, if not call method to spawn a health pack
    //otherwise check to see if one exist and if it does is it's timer created with it
    //has been passed by Time.time (returns game clock time), if yes destroy the created
    //health pack.
    if (healthExist == false) 
    {
        spawnUntilFull ();
    } 
    else if (healthExist == true && Time.time > healthTimer)
    {
        //Error occuring here when trying to destroy
        //Destroy(transform.root.gameObject)    //destroys script, object scripts on, and prefab
        Destroy(this.gameObject);   //does same as Destroy(transform.root.gameObject
        healthExist = false;
    }
}

Transform NextFreePosition()
{
    //free space
    foreach (Transform childPositionGameObject in transform) 
    {
        //if no health packs located return location of child object to spawn new health pack
        if (childPositionGameObject.childCount == 0) 
        {
            return childPositionGameObject;
        }
    }
    return null;
}
void spawnUntilFull()
{
    //returns next free position in space
    Transform freePosition = NextFreePosition ();
    //if free slot is available
    if (freePosition && healthExist == false) 
    {
        //instantiates health object and places it in scene at coordinates received from
        //freePosition
        health = Instantiate (healthPackPrefab, freePosition.position, Quaternion.identity) as GameObject;
        //spawns enemy onto a position under the Parent (Enemy Formation)
        health.transform.parent = freePosition;
        //set bool to true to stop spawning
        healthExist = true;
        //seat HealthTimer to 5 seconds after creation for use in Update method
        healthTimer = Time.time + 5.0f;
    }
}

从脚本Unity3d C#中销毁由脚本创建的对象

当您调用Destroy((时,您实际上正在做的是销毁脚本。为了实现你想要的(摧毁健康包(,你只需在上面调用Destroy:

Destroy(health);

顺便说一句,为了避免使用Time.time的混乱代码,Destroy((有一个重载,它使用了两个参数:

Destroy(GameObject object, float delay);

这将有助于简化代码并使其更具可读性。

您可以在预制板上添加一个单独的脚本,其中包含自定义的DestroyObject方法。

创建对象后立即在该脚本上启动计时器。

现在,如果在一定时间内没有收集到,你很容易就会破坏这个物体。