简体   繁体   English

无法重新实例化/重生我在Unity3D中销毁的对象

[英]Can't re-instantiate/respawn object I've destroyed in Unity3D

I've 2 scripts. 我有2个脚本。 1 makes objects and the other destroys them. 1个制造物体,另一个摧毁它们。

I first press OnSave button which runs script #1 and creates my objects. 我首先按OnSave按钮,该按钮运行脚本#1并创建我的对象。 (there's more than one, although here in the script just shows one, I shortened for the sake of question) (有多个,尽管脚本中的此处仅显示了一个,但为方便起见,我将其缩短了)

then I press OnReset button which destroys created objects/prefabs. 然后我按OnReset按钮,这会破坏创建的对象/预制件。 But when I press OnSave again, it doesn't recreated objects. 但是当我再次按OnSave时,它不会重新创建对象。

These 2 scripts are attached to 2 different gameObjects 这2个脚本已附加到2个不同的gameObjects

here's what I have: 这是我所拥有的:

script #1: 脚本1:

public GameObject go;
public static volatile List<GameObject> prefab = new List<GameObject>();


public class OnSave : MonoBehaviour
{
public void Start2()
{
                var newObj = Instantiate(go);
                newObj.transform.parent = GameObject.Find("MOOSE").transform;
                newObj.GetComponent<Renderer>().material.color = Color.green;
                newObj.transform.localPosition = new Vector3(1.0,1.0,1.0)
                prefab.Add(newObj);


}
}

script #2 脚本2

public class OnReset: MonoBehaviour
{
foreach (GameObject obj in prefab)
{
Destroy(obj);
}
}

I'm using the latest version of Unity. 我正在使用最新版本的Unity。 I have to destroy these objects and recreate them 我必须销毁这些物体并重新创建它们

You need a prefab to be able to reinstantiate the object, but the operation of destroying and reinstantiating is heavy, so normally you use a pooling manager of sort like https://www.assetstore.unity3d.com/en/#!/content/47242 (disclaimer: I'm the author of this one) or https://www.assetstore.unity3d.com/en/#!/content/23931 . 您需要一个预制板才能重新实例化该对象,但是销毁和重新实例化的操作很繁琐,因此通常您使用类似于https://www.assetstore.unity3d.com/en/#!/content的池管理器/ 47242 (免责声明:我是这一本书的作者)或https://www.assetstore.unity3d.com/en/#!/content/23931

Here's the official Unity totorial about pooling objects: https://unity3d.com/learn/tutorials/topics/scripting/object-pooling 这是有关对象池的Unity官方教程: https ://unity3d.com/learn/tutorials/topics/scripting/object-pooling

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

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