奇怪的Unity预制行为?

时间:2019-04-28 14:05:30

标签: c# unity3d

在场景的开始,脚本生成了5个Prefab的克隆,其中包括: 带有碰撞检测器的小石头和本身包括的大石头:精灵。为了提供更好的想象力,我提供了图片:

Picture 1

Picture 2

如您所见,Rock元素中的Big_rock已在预制件中正确连接。

每当我要使用Destroy(Big_rock)时,它实际上会破坏Big_rock 从下一个PREFAB ,我真的不知道为什么会这样。

1 个答案:

答案 0 :(得分:0)

问题似乎是您在实例化BigRock时没有更改引用。 BigRock作为预制件,与生成的GameObject不同。您应该有第二个变量,它引用新产生的岩石。

请记住,第一个在场景中不存在,因此您应该将实例化的一个保存在场景中。

// This will be the reference to the PREFAB
public GameObject big_rock;
// This will be the referenced to the new spawned gameobject
private GameObject spawned_big_rock;

private void SpawnRock()
{
    GameObject gameobjectThatWeJustSpawned = Instantiate(big_rock);
    // We set the reference to the one that was spawned
    spawned_big_rock = Instantiate(big_rock);
}

public void DestroyRock()
{
    // We destroy the one that was spawned
    Destroy(spawned_big_rock);
}