Search Unity

C# mesh transform applied in both editor and play mode

Discussion in 'Scripting' started by kulnor, Apr 11, 2021.

  1. kulnor

    kulnor

    Joined:
    May 23, 2016
    Posts:
    7
    I have written a C# script that transform all meshes under parent a transform, the goal being to project flat country maps onto a sphere. The script class has [ExecuteInEditMode] and I have an associated Editor class.

    I loop over all children and this works fine in editor mode. I basically make a copy of the sharedMesh, then apply the transform, and set the new mesh on the meshFilter.
    Code (CSharp):
    1.  
    2. Mesh mesh = Mesh.Instantiate(geoMeshObject.MeshFilter.sharedMesh);
    3. MeshToSphere(mesh, Radius);
    4. geoMeshObject.ClonedMesh = mesh;
    5. geoMeshObject.MeshFilter.mesh = geoMeshObject.ClonedMesh;
    6.  
    However, when I go to play mode from the editor, the transform gets applied a second time to the meshes. Basically it appears the shareMesh I get in play mode in not the original one, but the already transformed one. I was more expecting the play mode to start from a clean environment.

    What is the correct approach for this type of script that procedurally alter/transform meshes in editor mode? I feel I'm missing some basic understanding of how sharedMesh and mesh exist in editor and play mode.

    Any help/guidance appreciated!

    Note that CopyMesh uses:
    Code (CSharp):
    1.  
    2. Mesh clonedMesh = Instantiate<Mesh>(originalMesh);
    3.  
    I also tried to manually copy the mesh (but same results)
    Code (CSharp):
    1.  
    2. Mesh clonedMesh = new Mesh();
    3. clonedMesh.name = "clone";
    4. clonedMesh.vertices = originalMesh.vertices;
    5. clonedMesh.triangles = originalMesh.triangles;
    6. clonedMesh.normals = originalMesh.normals;
    7. clonedMesh.uv = originalMesh.uv;
    8.  

    Script disabled in Editor
    Screen Shot 2021-04-11 at 10.11.02 AM 1.png

    Scripts enabled in Editor
    Screen Shot 2021-04-11 at 10.11.40 AM.png


    Double transform in Play Mode
    Screen Shot 2021-04-11 at 10.23.33 AM.png
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    I'm not super-fond of ExecuteInEdit mode generally, just because of this conflation of when things happen.

    The approach I favor is a separate editor-only method that operates on the current
    Selection
    :

    https://docs.unity3d.com/ScriptReference/Selection.html

    You can conditionally compile editor code into your main game scripts with:

    Code (csharp):
    1. #if UNITY_EDITOR
    2.   // code here that ONLY works in editor, will never build to target
    3. #endif
    And partial classes can even help keep it in another file entirely, to reduce clutter.