HELP Memory Filled Refactoring Gameobject Textures

Hi i need to clean the memory up after i refactor the gameobject and move to the next any input would be great

The memory fills up to 17gigs and haults and crashes unity HELP

using Dummiesman;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
//using UnityFBXExporter;
public class ObjFromFile : MonoBehaviour
{

   

    void Start()
    {

    
        StartCoroutine(Run());
  
    }

    IEnumerator Run() {

        //file path
        //string filePath = @"F:\VATICMOD\Data\azeroth_37_31.obj";
        //string filePath = @"D:\Models\world\maps\silvermooncity\silvermooncity_44_12.obj";
        string filePath = "Assets/Resources/world/maps/silvermooncity/";
        string[] filePaths = System.IO.Directory.GetFiles(filePath);


        int countFound = 0;



        if (filePaths != null && filePaths.Length > 0)
        {
            for (int i = 0; i < filePaths.Length; i++)
            {

                // string filePath = "Assets/Resources/world/maps/silvermooncity/silvermooncity_42_11.obj";
                if (!File.Exists(filePaths[i]))
                {
                    Debug.LogError("Please set FilePath in ObjFromFile.cs to a valid path.");

                }

                if (filePaths[i].Contains(".obj"))
                {
                    //create stream and load
                    GameObject loadedObj = new OBJLoader().Load(filePaths[i]);

                    Debug.Log(loadedObj.name);



                    foreach (Transform g in loadedObj.transform)
                    {
                        GameObject f = g.gameObject;
                        string n = f.name;
                        f.GetComponent<Renderer>().material.shader = Shader.Find("Standard");
                        f.GetComponent<Renderer>().material.SetFloat("_Glossiness", 0);
                        Debug.Log(g.name);
                        if (f.name == "0")
                        {
                            n = loadedObj.name;
                        }
                        SaveRTToFile(f.GetComponent<Renderer>().material.GetTexture("_MainTex") as Texture2D, n);
                    }




                    string newPath = "F:/VATICMOD/TESTExport/" + loadedObj.name;




                    //UnityFBXExporter.FBXExporter.ExportGameObjToFBX(loadedObj, newPath);


                    Destroy(loadedObj);

                    FileUtil.CopyFileOrDirectory(filePaths[i], newPath);

                    Resources.UnloadUnusedAssets();
                    GC.Collect();
                    //create stream and load
                    GameObject loadedObj2 = new OBJLoader().Load(newPath);

                    foreach (Transform g in loadedObj2.transform)
                    {
                        GameObject f = g.gameObject;
                        string n = f.name;


                        string filename = "F:/VATICMOD/TESTExport/" + g.gameObject.name + ".jpg";
                        var rawData = System.IO.File.ReadAllBytes(filename);
                        Texture2D tex = new Texture2D(2, 2); // Create an empty Texture; size doesn't matter (she said)
                        tex.LoadImage(rawData);
                        g.gameObject.GetComponent<Renderer>().material.mainTexture = tex;


                        f.GetComponent<Renderer>().material.shader = Shader.Find("Standard");
                        f.GetComponent<Renderer>().material.SetFloat("_Glossiness", 0);
                        Debug.Log(g.name);
                        if (f.name == "0")
                        {
                            n = loadedObj.name;
                        }
                        //SaveRTToFile(f.GetComponent<Renderer>().material.GetTexture("_MainTex") as Texture2D, n);
                    }

                    Destroy(loadedObj2);

                    Resources.UnloadUnusedAssets();
                    GC.Collect();
                }
                Resources.UnloadUnusedAssets();
                GC.Collect();
            }
        }


        yield return new WaitForSeconds(0);


    }
    public static void SaveRTToFile(Texture2D t ,string filename)
    {
       // RenderTexture rt = t as RenderTexture;

        //RenderTexture.active = rt;
        Texture2D tex = new Texture2D(t.width, t.height, TextureFormat.RGB24, false);
        //tex.ReadPixels(new Rect(0, 0, t.width, t.height), 0, 0);
        //RenderTexture.active = null;

        byte[] bytes;
       // bytes = t.EncodeToPNG();
        bytes = t.EncodeToJPG(25);
       // bytes = t.EncodeToTGA();
        //string path = AssetDatabase.GetAssetPath(t) + "TESTExport/" + filename +  ".png";
        string path = AssetDatabase.GetAssetPath(t) + "TESTExport/" + filename + ".jpg";
        System.IO.File.WriteAllBytes(path, bytes);
        AssetDatabase.ImportAsset(path);
        Debug.Log("Saved to " + path);
    }


}

Line 98 and 133 create textures you never call Destroy on.

Actually, it doesn’t appear you’re using the new texture tex you create on 133 at all - you could comment that right out.

And note there are built-in functions to save/load textures, i.e. to save:

string path = "Assets/test.asset";
if (AssetDatabase.LoadAssetAtPath<Texture2D>(path) != null) AssetDatabase.DeleteAsset(path); // delete if already exists
AssetDatabase.CreateAsset(tex, path); // save texture to path

And to load…

Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
if (tex != null)
{
  Debug.Log("got texture");
}

The main thing is, assigning a texture asset reference to a material means the texture will stay assigned to the texture property. If you load the bytes and create new texture and assign it, the material will end up empty again.

Thanks for the help yeah nothing has worked yet im still trying

im not using assets inside unity im just trying to change all the images from png to jpg to reduce the sizes

still filling up the ram to 99% and whole system fails…

i suppose just writing a C# program to do this out side of unity is better but its fun working with the editor doing this advanced stuff…

and yes the second load object and textures is not needed i had it there to see the final product back in the editor working with one terrain at a time i can take that out and it would save some ram

I made a new project just to do this heres the code i refactored the script a bit too

using Dummiesman;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ObjFromFile : MonoBehaviour
{

    public string sourceFilePath;
    public string destFilePath;
    public int jpgCompressionlvl;

    void SaveRTToFile(Texture2D t, string filename)
    {

        Texture2D tex = new Texture2D(t.width, t.height, TextureFormat.RGB24, false);


        byte[] bytes;

        bytes = t.EncodeToJPG(jpgCompressionlvl);

        string path = AssetDatabase.GetAssetPath(t) + "NewObjects/" + filename + ".jpg";
        System.IO.File.WriteAllBytes(path, bytes);
        AssetDatabase.ImportAsset(path);
        Debug.Log("Saved to " + path);
        Destroy(tex);
    }

    void Start()
    {

        DontDestroyOnLoad(this.gameObject);
        //StartCoroutine(Run());
     
    }

    void OnGUI()
    {
     

     

        if (GUI.Button(new Rect(10, 70, 50, 30), "Click"))
            StartCoroutine(Run());
    }




    IEnumerator Run() {


        string[] filePaths = System.IO.Directory.GetFiles(sourceFilePath);

        Debug.Log("Found " + filePaths.Length + " Files");

        int countFound = 0;

        if (filePaths != null && filePaths.Length > 0)
        {
            for (int i = 0; i < filePaths.Length; i++)
            {

        
                if (!File.Exists(filePaths[i]))
                {
                    Debug.LogError("Please set FilePath in ObjFromFile.cs to a valid path.");

                }

                if (filePaths[i].Contains(".obj"))
                {
                    //create stream and load
                    GameObject loadedObj = new OBJLoader().Load(filePaths[i]);

                    foreach (Transform g in loadedObj.transform)
                    {
                        GameObject f = g.gameObject;
                        string n = f.name;
                        f.GetComponent<Renderer>().material.shader = Shader.Find("Standard");
                        f.GetComponent<Renderer>().material.SetFloat("_Glossiness", 0);
         
                        if (f.name == "0")
                        {
                            n = loadedObj.name;
                        }
                        SaveRTToFile(f.GetComponent<Renderer>().material.GetTexture("_MainTex") as Texture2D, n);
                    }

                    //UnityFBXExporter.FBXExporter.ExportGameObjToFBX(loadedObj, newPath);


                    Destroy(loadedObj);

                    try { FileUtil.CopyFileOrDirectory(filePaths[i], destFilePath + "/" + loadedObj.name + ".obj"); } catch { }

                 

                    Resources.UnloadUnusedAssets();
                    EditorUtility.UnloadUnusedAssetsImmediate();
                    GC.Collect();


                    //create stream and load
                    GameObject loadedObj2 = new OBJLoader().Load(destFilePath +"/"+ loadedObj.name +".obj" );

                    foreach (Transform g in loadedObj2.transform)
                    {
                        GameObject f = g.gameObject;
                        string n = f.name;


                        string filename =  destFilePath + "/" + g.gameObject.name + ".jpg";
                      
                        var rawData = System.IO.File.ReadAllBytes(filename);
                        Texture2D tex = new Texture2D(2, 2); // Create an empty Texture; size doesn't matter (she said)
                        tex.LoadImage(rawData);
                        g.gameObject.GetComponent<Renderer>().material.mainTexture = tex;


                        f.GetComponent<Renderer>().material.shader = Shader.Find("Standard");
                        f.GetComponent<Renderer>().material.SetFloat("_Glossiness", 0);
                        Debug.Log(g.name);
                        if (f.name == "0")
                        {
                            n = loadedObj.name;
                        }
                        Destroy(tex);
                    }
                
                    Destroy(loadedObj2);

           
                }


                Resources.UnloadUnusedAssets();
                EditorUtility.UnloadUnusedAssetsImmediate();
                GC.Collect();

               // SceneManager.LoadScene("2");

            }
        }


        yield return new WaitForSeconds(0);


    }
      
  
  



}

and i thought that reloading into a blank scene would drop the ram but it throws this error

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.get_name () (at <29ad182faa3f478c9310d6a2e7143c15>:0)
ObjFromFile+<Run>d__6.MoveNext () (at Assets/OBJImport/Samples/ObjFromFile.cs:109)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <29ad182faa3f478c9310d6a2e7143c15>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
ObjFromFile:OnGUI() (at Assets/OBJImport/Samples/ObjFromFile.cs:48)

well i guess figuring out a work around dumping scenes and restarting after each piece is done and checking the folder and skipping whats been done already is going to happen.

or

spend some money and try a couple 400gig ddr3 sata dimms is on the fun list could opt for a sata dimm with a connector and get a 1 or 2 tb ssd could be interesting to see the results

Tink i got it memory holding around 4 gigs and unloading correctly

here is the code im happy lo

using Dummiesman;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ObjFromFile : MonoBehaviour
{

    public string sourceFilePath;
    public string destFilePath;
    public int jpgCompressionlvl;
    Texture2D tex;
    void SaveRTToFile(Texture2D t, string filename)
    {

         tex = new Texture2D(t.width, t.height, TextureFormat.RGB24, false);


        byte[] bytes;

        bytes = t.EncodeToJPG(jpgCompressionlvl);

        string path = AssetDatabase.GetAssetPath(t) + "NewObjects/" + filename + ".jpg";
        System.IO.File.WriteAllBytes(path, bytes);
        AssetDatabase.ImportAsset(path);
        Debug.Log("Saved to " + path);
        Destroy(tex);
    }

    void Start()
    {

        DontDestroyOnLoad(this.gameObject);
        //StartCoroutine(Run());
      
    }

    void OnGUI()
    {
      

      

        if (GUI.Button(new Rect(10, 70, 50, 30), "Click"))
            StartCoroutine(Run());
    }




    IEnumerator Run() {


        string[] filePaths = System.IO.Directory.GetFiles(sourceFilePath);

        Debug.Log("Found " + filePaths.Length + " Files");

        int countFound = 0;

        if (filePaths != null && filePaths.Length > 0)
        {
            for (int i = 0; i < filePaths.Length; i++)
            {
                yield return new WaitForSeconds(0f);

                if (!File.Exists(filePaths[i]))
                {
                    Debug.LogError("Please set FilePath in ObjFromFile.cs to a valid path.");

                }

                if (filePaths[i].Contains(".obj"))
                {

                    string[] destfile = System.IO.Directory.GetFiles(destFilePath);
                   
                    string[] sourcefilenamesplit = filePaths[i].Split('\\');
                    Debug.Log(sourcefilenamesplit.Length.ToString());
                    Debug.Log(sourcefilenamesplit[1]);
                   // int lastinfilenameint = sourcefilenamesplit.Length;
                    bool filefound = false;
                    foreach (string file in destfile)
                    {
                        yield return new WaitForSeconds(0f);
                        if (file.Contains(sourcefilenamesplit[sourcefilenamesplit.Length - 1])) {
                            filefound = true;
                        }
                    }

                    if (filefound) {
                        //pass this file its already created
                        Debug.Log("FILE FOUND SKIPPING");
                    }
                    else
                    {


                        //create stream and load
                        GameObject loadedObj = new OBJLoader().Load(filePaths[i]);



                        foreach (Transform g in loadedObj.transform)
                        {
                            yield return new WaitForSeconds(0f);
                            GameObject f = g.gameObject;
                            string n = f.name;
                            f.GetComponent<Renderer>().material.shader = Shader.Find("Standard");
                            f.GetComponent<Renderer>().material.SetFloat("_Glossiness", 0);

                            if (f.name == "0")
                            {
                                n = loadedObj.name;
                            }
                            SaveRTToFile(f.GetComponent<Renderer>().material.GetTexture("_MainTex") as Texture2D, n);
                        }

                        //UnityFBXExporter.FBXExporter.ExportGameObjToFBX(loadedObj, newPath);


                        Destroy(loadedObj);

                        try { FileUtil.CopyFileOrDirectory(filePaths[i], destFilePath + "/" + loadedObj.name + ".obj"); } catch { }



                        Resources.UnloadUnusedAssets();
                        EditorUtility.UnloadUnusedAssetsImmediate();
                        GC.Collect();
                        yield return new WaitForSeconds(0f);
                    }
                    ////create stream and load
                    //GameObject loadedObj2 = new OBJLoader().Load(destFilePath +"/"+ loadedObj.name +".obj" );

                    //foreach (Transform g in loadedObj2.transform)
                    //{
                    //    GameObject f = g.gameObject;
                    //    string n = f.name;


                    //    string filename =  destFilePath + "/" + g.gameObject.name + ".jpg";

                    //    var rawData = System.IO.File.ReadAllBytes(filename);
                    //    Texture2D tex = new Texture2D(2, 2); // Create an empty Texture; size doesn't matter (she said)
                    //    tex.LoadImage(rawData);
                    //    g.gameObject.GetComponent<Renderer>().material.mainTexture = tex;


                    //    f.GetComponent<Renderer>().material.shader = Shader.Find("Standard");
                    //    f.GetComponent<Renderer>().material.SetFloat("_Glossiness", 0);
                    //    Debug.Log(g.name);
                    //    if (f.name == "0")
                    //    {
                    //        n = loadedObj.name;
                    //    }
                    //    Destroy(tex);
                    //}

                    //Destroy(loadedObj2);

                    yield return new WaitForSeconds(0f);
                }


                Resources.UnloadUnusedAssets();
                EditorUtility.UnloadUnusedAssetsImmediate();
                GC.Collect();
                yield return new WaitForSeconds(0f);
                SceneManager.LoadScene("2");

            }
        }


        yield return new WaitForSeconds(0);


    }
       
   
   



}

l