PrefabUtility.CreatePrefab, what's going on here?

I have been able to save my generated prefab during run time, but not without issue. I had to avoid using some “creation code” in order to get it to save properly. To better understand Unity, I’m just wondering why.

Here is an example code and what happens:

if (Input.GetKeyDown(KeyCode.Space) == true)
            {
                GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
    
                //UNCOMMENT THIS LINE AND THE MESHFILTER COMPONENT AND MATERIAL WILL BE MISSING
                //float uselessVariable = obj.GetComponent<MeshFilter>().mesh.bounds.size.x;
    
                //UNCOMMENT THIS LINE AND THE MATERIAL WILL BE MISSING
                //obj.GetComponent<Renderer>().material.color = Color.red;
    
                PrefabUtility.CreatePrefab("Assets/Resources/Prefabs/StarShips/" + "TestSavePreFab" + ".prefab", obj);
            }

I can understand that altering the material will cause it not to save (you probably have to save the “new” material separately), but simply calling mesh.bounds.size will remove the filter? I don’t understand.

Your doing something really strange here. You’re mixing runtime and editor code which screams for trouble. Accessing “.mesh” or “.material” will cause the Mesh / Material to be duplicated. Those methods will throw a warning / error when used at edit time. Inside the editor you must only use sharedMesh and sharedMaterial. Of course if you want to actually change something in the material you have to duplicate it yourself and save it as material.

The general advice i can give you is: Do not execute editor features at runtime. Why do you try to create prefabs at runtime? Why can’t you do that in the editor? If the code is in a runtime class (i.e. MonoBehaviour) you can’t build your game anyways. If you want to create an editor extension then stay away from runtime.