【问题标题】:Unity instantiate new objects after 1 second of destroying previousUnity 在销毁前一个对象 1 秒后实例化新对象
【发布时间】:2015-12-23 12:35:32
【问题描述】:

我的代码有问题。我无法让我的立方体对象在销毁前一个立方体后 1 秒自动显示新的。这是我的代码:

void OnTriggerEnter(其他对撞机){

    if (other.gameObject.CompareTag ("cube1")) { 
        other.gameObject.SetActive (false);
        makenew ();

    }

}

IEnumerator makenew ()
{
    yield return new WaitForSeconds (1f);
    GameObject cube = Instantiate (cubePrefab) as GameObject;
    gameObject.SetActive (true);

}

}

【问题讨论】:

  • 所以你是在给自己打电话gameObject.SetActive (true);? :)

标签: unity3d


【解决方案1】:

你也可以这样做:

    if (other.gameObject.CompareTag ("cube1")) { 
        other.gameObject.SetActive (false);
        Invoke("makenew", 1.0f);

    }

}

void makenew ()
{

    GameObject cube = Instantiate (cubePrefab) as GameObject;
    gameObject.SetActive (true);

}

由于我不知道你在做什么,我的疑惑就在这里:

other.gameObject 是您停用的立方体。 (第一个游戏对象)

GameObject cube 是新的。 (第二个游戏对象)

使用此代码:gameObject.SetActive (true); 您正在使实际的第三个游戏对象(具有此代码的脚本的那个)变为活动状态,我可能猜到它已经是,不是?我想表达的是,使用此代码,您正在调用脚本的所有者。这可以吗?还是您想激活“其他”旧立方体,例如:

other.gameObject.SetActive (true);?

这样你就会有 2 个立方体。旧的(其他)和新的(立方体)。只是一个疑问。

已编辑:我怀疑gameObject.SetActive(true); 这行不是 OP 意图。他的 prefab 默认是停用的,所以 makenew() 方法应该是这样的:

void makenew ()
    {

        GameObject cube = Instantiate (cubePrefab) as GameObject;
        cube.SetActive (true);

    }

【讨论】:

  • 它可以工作,但我的立方体没有显示在我的屏幕上。我在我的层次立方体(克隆)上看到,但它不是黑色的,它是灰色的。
  • 你的预制件是默认激活的吗?如果在创建多维数据集后没有放置:cube.SetActive(true);
  • 我解决了所有问题。非常感谢你。我改变这条线 gameObject.SetActive (true);到 cube.SetActive (true);一切都很完美。
  • 太棒了。我会用正确的代码更新答案。
【解决方案2】:

这是因为你应该使用 StartCoroutine() 方法而不是仅仅调用 makenew()。试试这个:

StartCoroutine(makenew());

这是文档的链接: MonoBehaviour.StartCoroutine

【讨论】:

    【解决方案3】:

    你忘了StartCoroutine

    那就试试吧:

    void OnTriggerEnter (Collider other){
    
    if (other.gameObject.CompareTag ("cube1")) { 
        other.gameObject.SetActive (false);
        StartCoroutine (makenew ());
    
    }
    

    }

    【讨论】:

      【解决方案4】:

      只提一件事——如果游戏对象被禁用,协程也会停止 (See this answer)。所以你可能需要使用 Invoke() 来代替:

          if (other.gameObject.CompareTag ("cube1")) { 
              other.gameObject.SetActive (false);
              Invoke("makenew", 1f);
      
          }
      
      }
      
      void makenew ()
      {
          GameObject cube = Instantiate (cubePrefab) as GameObject;
          gameObject.SetActive (true);
      }
      

      如果您需要更好地了解正在发生的事情,请参阅this quick tutorial of Invoke

      不过,其他答案也很有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-01
        相关资源
        最近更新 更多