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

Sequentially Rename Texture Files

Discussion in 'Scripting' started by cansub, May 28, 2018.

  1. cansub

    cansub

    Joined:
    May 30, 2017
    Posts:
    15
    I have an array of texture files for a model. I am using an if statement to find out if a texture.name.contains("Lips") and then renaming it to my naming convention and then adding a sequence on it. The issue that I am running into is that it will rename the first file and write it, but then it will say that it cannot write a file that already exists on the next loop. I must be using a counter incorrectly.

    Code (CSharp):
    1. public void ChangeTextureNames()
    2.     {
    3.         _applicationPath = Application.dataPath;
    4.         texturePath = string.Format("{0}{1}{2}{3}", _applicationPath, "/Resources/Models/", characterSelection, "/Textures/");
    5.  
    6.         foreach (Texture texture in texturesThatHaveBeenFound)
    7.         {
    8.             int count = 1;
    9.             fileName1 = string.Format("{0}{1}{2}", texturePath, texture.name, ".jpg");
    10.             fileName2 = string.Format("{0}{1}{2}{3}{4}", texturePath, characterSelection, "_Lips_", count, ".jpg");
    11.  
    12.             if (texture.name.Contains("Lips"))
    13.             {
    14.                 File.Move(fileName1, fileName2);
    15.             }
    16.             count++;
    17.         }
    18.     }
    The error that I get is:
    IOException: Win32 IO returned ERROR_ALREADY_EXISTS. Path:

    There is the first file written (and the old one deleted) but it seems on the second loop that it isn't increasing the counter by 1 and therefore not able to overwrite the file because it already exists. There are 8 textures in the array that fits the if statement of "Lips".
     
  2. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,083
    In your 'foreach' loop you've got "count = 1" which means the filename2 will be the same every time. You need to put that 'count = 1' line before the start of the foreach loop.
     
  3. cansub

    cansub

    Joined:
    May 30, 2017
    Posts:
    15
    That got it. I am feeling a bit like a stooge as I spent hours on this, knowing how it should work, and for some reason I did not place the counter right there. Thanks for the assist!
     
  4. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,083
    No problem, it's easy to get mixed up with all the variable scope stuff.