Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[Solved] Copy a file, then immediately load the copy?

Discussion in 'Editor & General Support' started by CloudyVR, Sep 5, 2017.

  1. CloudyVR

    CloudyVR

    Joined:
    Mar 26, 2017
    Posts:
    714
    Consider the following script which takes an existing texture object, creates a copy of the texture file, copies that file to Resources directory, then immediately loads the new copy as the texture object:
    Code (csharp):
    1.  
    2. string m_resourceFolder = "RoomTextures1";
    3.  
    4. Texture2D texture = myTexture; // Grab a reference to some texture we created earlier.
    5. FileUtil.ReplaceFile (
    6.     AssetDatabase.GetAssetPath (texture), // Get current file path with extension.
    7.     toPath + Path.GetFileName(AssetDatabase.GetAssetPath (texture)) // The folder to place the new file.
    8. );
    9. myTexture = Resources.Load<Texture2D>(m_resourceFolder + "/" + texture.name); // Try to load the copied file.
    10.  
    When I run the above, I notice that the output for myTexture is null due to the copy not being created immediately, I must run it twice, or call that last line some time in the future then it works as expected.

    How do I create a copy of a file and then reference that copy immediately?

    Thanks.
     
  2. Zenix

    Zenix

    Joined:
    Nov 9, 2009
    Posts:
    213
    Try calling AssetDatabase.Refresh() before the load.
     
    lclemens and CloudyVR like this.
  3. CloudyVR

    CloudyVR

    Joined:
    Mar 26, 2017
    Posts:
    714
    That worked!!! Thanks!
     
  4. CloudyVR

    CloudyVR

    Joined:
    Mar 26, 2017
    Posts:
    714
    Because I was working with textures and compression I found that Unity was not actually compressing the new textures as it showed the message: "Not Yet Compressed".

    In my script, after setting the texture format, I had to reimport the asset like so:

    Code (csharp):
    1. AssetDatabase.Refresh()          
    2. Texture2D newTexture = Resources.Load<Texture2D> (m_resourceFolder + "/" + texture.name);
    3. newTexture.format = yourDesiredFormat; //set the compression format
    4.  
    5. AssetDatabase.ImportAsset( AssetDatabase.GetAssetPath( newTexture ) ); // Re-import texture file so it will be successfully compressed to desired format.
    6.  
    7. EditorUtility.CompressTexture (newTexture, TextureFormat.Whatever, TextureCompressionQuality.Normal); // Now compress the texture.
    8.  
    Now the new textures show as being compressed!
     
    Last edited: Sep 5, 2017