Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Instantiating an object when prefab is dragged in the scene view in editor mode

Discussion in 'Scripting' started by JFR, Jan 1, 2022.

  1. JFR

    JFR

    Joined:
    Feb 21, 2014
    Posts:
    65
    Hi all, since most of the main prefabs I instantiate at run-time contain a reference to a scriptable object with the actual reference to the visual prefab (the one that will actually appear at the instantiation position), it makes it impossible while in editor mode to see what the actual object will look like if I drag it the main prefab on the scene view. Of course I can always click on the visual ref prefab in the inspector and drag this one on screen instead, but I know from experience that for larger projects this can actually become bothersome.

    So the thing I’m trying to do is attach an editor script to the main prefab and detect the drag and drop on the scene view event so I can instantiate the visually referenced prefab in editor mode at the main prefab’s location in the scene view. When the user enters playmode, these instances are destroyed. So far I have not had any success since it seems impossible to attach an editor script to a prefab.

    Is there any way I can do this?
    Thanks,
    -Jeff
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,749
    Usually you just make a custom editor with a button that calls the factory to make the things transiently in scene. You can set flags (part of the .hideFlags) property to make sure they don't get inadvertently saved to a scene.

    You're welcome to take an example here:

    https://gist.github.com/kurtdekker/68b3fd9d4202888b4afc17b32eed6790

    It's a collection of GameObjects, a ScriptableObject in this case, but when selected you can click an custom inspector window button to instantiate a copy of everything in the collection so you can see it all at once.
     
  3. JFR

    JFR

    Joined:
    Feb 21, 2014
    Posts:
    65
    That’s really interesting, thanks for the answer, I will surely try to implement it! Appreciate the code example, makes it clearer.
     
    Last edited: Jan 2, 2022