Crazy Construction Destruction of GameObjects
Can anybody explain what crazy stuff is going on here?
I have a scene with only one GameObject with only this script:
public class NsTemp : MonoBehaviour
{
NsTemp()
{
Debug.Log("I am constructed");
}
~NsTemp()
{
Debug.Log("I am destructed");
}
void Awake()
{
Debug.Log("I am Awake");
}
void Start()
{
Debug.Log("I am Start");
}
void OnDestroy()
{
Debug.Log("I am Destroy");
}
private void OnApplicationQuit()
{
Debug.Log("I am the Application Quit!");
}
}
When I run Playmode and then exit it I get this in the console: (red line where I pressed exit Playmode)
Way is it constructed and destructed so many times? If someone could go through what happens line by line that would be great :-)
The reason I ask is that I run into a problem with my application where I created a non unity class in Awake (with new). That class opens some tcp ip sockets. When I exit play mode I expected those objects to be destroyed (by the garbage collector) and the cleanup code I have in the destructor would close the socket but that doesn't happen. If I later run Playmode again the GameObject gets deleted and the class with the socket gets garbage collected.
To boil my question down: Way isn't the GameObject garbage collected when I exit Playmode but when I enter it again next time?
This is just getting stranger. I can now see that destructors are run on in scripts that I havn't even placed in the scene at all. This is very confusing.
Your answer
![](https://koobas.hobune.stream/wayback/20220612132015im_/https://answers.unity.com/themes/thub/images/avi.jpg)