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

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:

string m_resourceFolder = "RoomTextures1";

Texture2D texture = myTexture; // Grab a reference to some texture we created earlier.
FileUtil.ReplaceFile (
    AssetDatabase.GetAssetPath (texture), // Get current file path with extension.
    toPath + Path.GetFileName(AssetDatabase.GetAssetPath (texture)) // The folder to place the new file.
);
myTexture = Resources.Load<Texture2D>(m_resourceFolder + "/" + texture.name); // Try to load the copied file.

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.

Try calling AssetDatabase.Refresh() before the load.

2 Likes

That worked!!! Thanks!

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:

AssetDatabase.Refresh()          
Texture2D newTexture = Resources.Load<Texture2D> (m_resourceFolder + "/" + texture.name);
newTexture.format = yourDesiredFormat; //set the compression format

AssetDatabase.ImportAsset( AssetDatabase.GetAssetPath( newTexture ) ); // Re-import texture file so it will be successfully compressed to desired format.

EditorUtility.CompressTexture (newTexture, TextureFormat.Whatever, TextureCompressionQuality.Normal); // Now compress the texture.

Now the new textures show as being compressed!