Home > database >  Unity freezes when adjusting the script to many objects
Unity freezes when adjusting the script to many objects

Time:10-27

I'm working on dropping the ball through Unity and getting the coordinates of the ball. Two things were applied: a script for physical action and a script for dropping a ball. I don't think there's a problem with the operation of these two codes. Because there's no problem when I apply the script to one ball. By the way, when the number of balls is increased to 100, Unity stops. I brought the part of the entire code that I think will be problematic:

if (Input.GetKeyUp("space"))
    {
        string name = this.gameObject.ToString();
        string num = name.Split('(')[1];

        //Debug.Log(transform.position.ToString());   
        Debug.Log(dir);
        filepath = dir   num   transform.position.ToString();
        Debug.Log(filepath);
        File.Create(filepath);
    }

I think there's a problem with the part which creates the file. I fixed that part like this:

FileStream fs = File.Create(filepath);                     
fs.Dispose();

After applying this, there was a slight movement when I played, but then it stopped again. I have to force myself to end through the work manager to use my Unity. Will I be able to get help? Since I am a beginner, I would be more grateful if you could explain it in easy words. My project version is 2018.4.36f1.

CodePudding user response:

It freezes because you are trying to do a lot of works just in one frame. It doesn't make sense why would you like to create a file for each position and gameobject. Maybe you are trying to log something?

If you are trying to log something, I would suggest you log to a simple file, not multiple files. It's not efficient for your application as well as for your debugging time.

For logging, you can use String Builder. Initialize your StringBuilder object in Start/Awake Method. StringBuilder sb = new StringBuilder();. Each time you want to add something to your log, do sb.Append("A log");.

Now for saving, you can save it OnDisable() or OnApplicationQuit(). To save -

System.IO.File.WriteAllText("FILE_PATH", sb.ToString());

I hope that serves.

  • Related