Search Unity

Loading a Prefab from resource and initiate a prefab inside it

Discussion in 'Editor & General Support' started by DavidNLN, Mar 14, 2019.

  1. DavidNLN

    DavidNLN

    Joined:
    Sep 27, 2018
    Posts:
    90
    Hello, I have a piece of code that loads a prefab from the resource folder, creates a new scene and then adds a prefab to it, the issue is that the prefab loaded is just an object, the prefab is broken.

    How can I load a prefab and initiate it without breaking the prefap "link"

    Code (CSharp):
    1.          
    2. var prefab = Resources.Load<GameObject>("prefabs/Root");
    3.  
    4. var newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
    5.                  
    6. SceneManager.SetActiveScene(newScene);
    7. var o = Object.Instantiate(prefab, Vector3.zero, Quaternion.identity);
    8. EditorSceneManager.SaveScene(newScene, "name.unity");
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    I haven't used any of these, but I found some functions that will probably be useful to you. These are editor-only, but I assume you would only need the prefab link in-editor.

    UnityEditor.PrefabUtility.InstantiatePrefab(Object prefab)
    UnityEditor.PrefabUtility.ConnectGameObjectToPrefab(GameObject instance, GameObject prefab)

    UnityEditor.PrefabUtility.ReconnectToLastPrefab(GameObject instance);
    UnityEditor.PrefabUtility.ResetToPrefabState(Object instance);
     
    DavidNLN likes this.
  3. DavidNLN

    DavidNLN

    Joined:
    Sep 27, 2018
    Posts:
    90
    Hi gambit,
    UnityEditor.PrefabUtility.InstantiatePrefab(Object prefab)
    Was just the thing! thanks, I dont know how I missed it I searched for an hour through the docs.