Instantiate an object in a prefab?

I have a setup with some nodes to form a path for a moving platform, each with a custom editor UI button to instantiate the currently selected node, and set the newly made node as the next node in the path. This works fine, except it breaks when I try to make a prefab of the setup so I can drag-and-drop in more moving platforms later.


When I make it a prefab, everything seems fine at first - I can make a new node, and it’s set as the next one along the path. However, the editor doesn’t mark the first node as having been modified from the prefab, so when I hit play it reverts to the prefab - and the connection to the new node breaks. If I drag and drop in the new node as reference it works fine, but I wanted to try and make the button do all the work so I wouldn’t need to worry about having to drag and drop for every node.


Is there a way to force the prefab to recognize that there’s been an update when pressing the button? I’m guessing it’s just not recognizing it, since I’m using custom UI. Is there a more graceful way to fix this?

Thanks for the help! I managed to get it working with customClass = (customClass)target and PrefabUtility.RecordPrefabInstancePropertyModifications - however, I’m not using SerializedProperty and SerializedObject since I didn’t really realize that they were better to use, and I don’t have any experiecne using them. Since I’m not using them, though, I can’t Undo the creation of the new pathing nodes. This isn’t the worst thing in the universe, but it would be nice. I tried a few different things with SerializedObject and couldn’t quite figure out how to get it working, can anyone shed some light on what I might be doing wrong? Here’s the relevant code, without using SerializedObject since I’m not sure how to correctly implement it:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(PlatformPathNode))]
public class PlatformPathNodeUI : Editor
{
    public override void OnInspectorGUI()
    {
        PlatformPathNode thisNode = (PlatformPathNode)target; //grabs the current object

        if (GUILayout.Button("Create New Node"))
        {
            int c = thisNode.transform.parent.childCount;
            Instantiate(thisNode.transform.GetComponent<PlatformPathNode>(), thisNode.transform.parent); //creates a clone of this node with the same parent
            PlatformPathNode newNode = thisNode.transform.parent.GetChild(c).GetComponent<PlatformPathNode>(); //grab the new node
            newNode.name = "Node " + (c - 1); //renames the new node to show its number in the child hierarchy

            thisNode.nextNode = newNode; //sets the newly made node as the next one in the path

            PrefabUtility.RecordPrefabInstancePropertyModifications(thisNode);
            Selection.activeObject = thisNode.nextNode; //set the new node as active

        }
    }
}