Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

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

Discussion in 'Editor & General Support' started by trappist-1, Sep 5, 2017.

  1. trappist-1

    trappist-1

    Joined:
    Mar 26, 2017
    Posts:
    546
    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:
    207
    Try calling AssetDatabase.Refresh() before the load.
     
    trappist-1 likes this.
  3. trappist-1

    trappist-1

    Joined:
    Mar 26, 2017
    Posts:
    546
    That worked!!! Thanks!
     
  4. trappist-1

    trappist-1

    Joined:
    Mar 26, 2017
    Posts:
    546
    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
unityunity