繁体   English   中英

UNITY SCRIPTS:被摧毁后在同一位置生成(3秒后)

[英]UNITY SCRIPTS:spawn in same location after getting destroyed(after 3 seconds)

嘿,有谁知道如何为对象在被子弹摧毁后重新生成 C# 脚本

有多种方法可以存档。

请注意,您也可以在没有协程的情况下完全工作,但这通常很糟糕

private float timer;

private bool isRespawning;
private GameObject clone;

private void DestroyObject(GameObject obj)
{
    isRespawning = true;
    timer = 3f;

    // first make a clone of the current Object
    var clone = Instantiate(obj, obj.transform.position, obj.transform.rotation, objtransform.parent);

    // disable the clone
    clone.SetActive(false);

    // Destroy the original
    Destroy(obj);
}

private void Update()
{
    if(Mathf.Approximately(timer,0f)) return;

    timer += Time.deltaTime;

    if(timer > 0) return;

    // Set the clone active
    clone.SetActive(true);
    timer = 0;
}

更简单的是协程:

private void DestroyAndRespawn(GameObject obj)
{
    StartCoroutine(DestroyAndRespawnRoutine(obj));
}

private IEnumerator DestroyAndRespawnRoutine(GameObject obj)
{
    // first make a clone of the current Object
    var clone = Instantiate(obj, obj.transform.position, obj.transform.rotation, objtransform.parent);

    // disable the clone
    clone.SetActive(false);

    // Destroy the original
    Destroy(obj);

    // Wait 3 seconds
    yield return new WaitForSeconds(3f);

    // Set the clone active
    clone.SetActive(true);
}

但是为什么要销毁对象并重新生成它呢? 您可以简单地仅禁用然后重新启用它

private void DestroyAndRespawn(GameObject obj)
{
    StartCoroutine(DestroyAndRespawnRoutine(obj));
}

private IEnumerator DestroyAndRespawnRoutine(GameObject obj)
{
    // disable the obj
    obj.SetActive(false);

    // Wait 3 seconds
    yield return new WaitForSeconds(3f);

    // Set the objactive
    obj.SetActive(true);
}

更新

由于您想在碰撞时调用它:

您将需要另一个 GameObject 作为重生/启用、禁用的管理器,因为您不能将该脚本附加到您禁用的对象 -> 也会禁用脚本并且永远不会重新启用该对象。

  1. 创建一个新的空游戏对象,例如名为“RespawnManager”
  2. 创建一个新的脚本 RespawnManager.cs:

     public class RespawnManager : MonoBehaviour { public static RespawnManager Singleton; private void Awake() { if(Singleton) { enabled = false; return; } Singleton = this; } private void DestroyAndRespawn(GameObject obj) { StartCoroutine(DestroyAndRespawnRoutine(obj)); } private IEnumerator DestroyAndRespawnRoutine(GameObject obj) { // disable the obj obj.SetActive(false); // Wait 3 seconds yield return new WaitForSeconds(3f); // Set the objactive obj.SetActive(true); } }
  3. 比你可以在碰撞时调用它

    OnCollisionEnter(Collision obj) { if (obj.gameObject.name != "bullet") return; // pass this GameObject to the manager RespawnManager.Singleton.DestroyAndRespawn(gameObject); }

集对象active为False。 使用

gameobject.SetActive(false);

你可以使用协程来做到这一点。

如果你使用Destroy(yourObject); ,该对象确实会被删除并且您无法访问。 您可以使用GameObject obj = Instantiate(...);将您的对象制作成预制件并在您想要的地方生成它GameObject obj = Instantiate(...); Obj 包含对新生成的对象的引用,而不是对预制件的引用,这意味着您稍后可以再次使用Destroy(obj);

暂无
暂无

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

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