繁体   English   中英

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

[英]Destroying an object created by a script from within the script Unity3d C#

不错,伙计们和女孩们在这方面需要一点帮助。 基本上,我是从处于打开位置的预制件实例化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;
    }
}

当您调用Destroy()时,您正在有效执行的操作正在破坏脚本。 要实现您想要的功能(销毁健康包),只需在其上调用Destroy即可:

Destroy(health);

附带说明一下,为了避免使用Time.time造成混乱的代码,Destroy()具有使用两个参数的重载:

Destroy(GameObject object, float delay);

这应该有助于简化您的代码并使之更具可读性。

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

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

现在,如果未在一定时间内收集到该物品,则可以轻松销毁该物品。

暂无
暂无

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

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