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.

Question Assigning Mesh or Texture2D to serialized variables don't save with the prefab

Discussion in 'Prefabs' started by Darkgaze, Oct 27, 2022.

  1. Darkgaze

    Darkgaze

    Joined:
    Apr 3, 2017
    Posts:
    361
    Hi . This is probably a basic question but I was wondering...

    I have a prefab which I open with Prefab mode. Then with an editor tool I assign a sharedMesh and a Texture2D that are instanced and not saved to disk.

    In a scene, these would get serialized in the scene since they are not references in the project view.

    But in prefabs, when you get out of the prefab mode after saving these changes, these instances of the mesh or texture are lost and None is shown in the instanced prefab in the scene that I just edited.

    How do I make them save? Is it possible to assign instances of object classes without having references in the Project on prefabs?
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    1,840
    My understanding of how Prefabs work is that any reference in a prefab must be an asset in itself. Any in-memory reference will be lost. Any in-scene reference cannot even be assigned (at least not in the Editor, not sure about scripting, but either way, it will end up being null/missing).

    In your case, you would have to save the instantiated Mesh as an asset, and then assign it to the shareMesh in the Prefab. Then it will persist.

    Alternatively, leave the Prefab sharedMesh null, possibly add another script that contains the required data to instantiate a mesh, and when the prefab instance runs OnEnable or Start or whatever - any time after entering playmode (at runtime) you can instantiate a Mesh and assign it to the instance of the prefab.

    Of course, if you have 1,000 instances you would have to do this 1,000 times, or have maybe a common class that instantiates the 10 meshes you need at runtime and the prefabs get the reference from that script.
     
  3. Darkgaze

    Darkgaze

    Joined:
    Apr 3, 2017
    Posts:
    361
    Yeah. Thanks a lot. I needed confirmation, but after several tests I've done, if I want to have those stored in the prefab, it can't live in the prefab file, only in the instance in the scene and as overrides, in new objects.

    That way, they are serialized in the scene and referenced. But the prefab assets don't have any reference.