Search Unity

Loading a Mesh at run time - possible bug?

Discussion in 'Scripting' started by KelsoMRK, Dec 2, 2010.

  1. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    So here's what I'm doing:

    1. Prefab that has a Mesh Renderer and Mesh Filter component attached - Mesh Filter has no Mesh
    2. Using Resource.Load() I load another GO that has the Mesh that I need
    3. I add that Mesh as the <MeshFilter>().mesh of the Prefab
    4. I continue to add various Components based on user selection - blah blah blah

    Everything appears to work ok the first time but then the GO that is Resource.Load'ed loses it's Mesh target in the Editor and I have to re-save from 3DSMax in order for it to come back.

    Is this a bug or something I am missing associated with Resource.Load?
     
  2. Tzan

    Tzan

    Joined:
    Apr 5, 2009
    Posts:
    736
    When you load a prefab with Resource.Load(), anything you do to that object is saved to disk as a permanent change to the file. So you could end up drastically changing that file.

    To avoid this, you need to make a new instance of the loaded object and make all changes to that.

    I'm not exactly sure what you are doing, no posted code, hopefully this fixes things for you.
     
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Indeed I should have posted - apologies:

    Code (csharp):
    1.  
    2. public GameObject guyTemplate;  // basic shell GO
    3.  
    4. void spawnGuy() {
    5.     buildGuy(guyTemplate);
    6.     Network.Instantiate(guytemplate, Vector3.zero, Quaternion.identity, 0);
    7. }
    8.  
    9. void buildGuy(GameObject newGuy) {
    10.     newGuy.name = "someName";
    11.     GameObject tempGO = Resources.Load("specificMesh") as GameObject;
    12.     Mesh tempMesh = tempGo.GetComponent<MeshFilter>().mesh;
    13.     newGuy.GetComponent<MeshFilter>().mesh = tempMesh;
    14. }
    15.  
    Looking in the Inspector - when everything is loaded the Mesh Filter of "specificMesh" changes from meshName to meshName Instance and my only guess is that the Network.DestroyPlayerObjects is destroying it upon exiting.
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    What Tzan said--instead of Resources.Load..., do Instantiate(Resources.Load...

    --Eric
     
  5. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Yup - was just about to come back here and say that it worked. :)

    Another quick follow-up as I was poking around today. Is there an easy way to add a GameObject as the child of another GameObject at run time?
     
  6. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Set transform.parent.

    --Eric