为什么我第二次实例化预制件时会出错?

Why do I get an error, when I instantiating prefab second time?

当我尝试向实例化的游戏对象添加预制件时,出现错误:

Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption

当我第一次调用这个脚本时,一切正常。有很多类似的问题和答案。但是,我无法解决我的问题。

感谢您的帮助:)

GameObject coralWoodBundle = Resources.Load("Base/coral_wood_bundle") as GameObject;
GameObject woodlBundle = Instantiate(coralWoodBundle) as GameObject;
woodlBundle.transform.SetParent(this.gameObject.transform);

相关脚本

public class FallingWoodPackScript: MonoBehaviour
{
    public List<FallingWoodScript> fallingWoodScripts;

    public void Start()
    {
        RefillWood();
    }

    public void RefillWood()
    {
        GameObject coralWoodBundle = Resources.Load("Base/coral_wood_bundle") as GameObject;
        GameObject woodlBundle = Instantiate(coralWoodBundle) as GameObject;
        woodlBundle.transform.SetParent(this.gameObject.transform);
        woodlBundle.transform.localPosition = new Vector3(1f, 2.7f, 0);
        woodlBundle.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, -90));
        fallingWoodScripts = new List<FallingWoodScript>();
        foreach (Transform child in woodlBundle.transform)
        {
            fallingWoodScripts.Add(child.GetComponent<FallingWoodScript>());
        }
    }
}

我很久以前就遇到过这个错误,在我看来它的措辞有点误导。

也许你这样理解更好:

Setting the parent TO a transform which resides in a prefab is disabled to prevent data corruption

我的猜测是您通过脚本调用 RefillWoodStartFallingWoodPackScript 引用 (=this) 实际上是 预制参考,因此this.gameObject.transform如错误所述a transform which resides in a prefab

确保仅在场景中的实际 实例 上调用 RefillWood(或 Start)。