mcpiroman / UnityNativeTool

Allows to unload native plugins in Unity3d editor
MIT License
184 stars 19 forks source link

DllManipulatorScript is not the last GameObject calling OnDestroy when scene is being destroyed. #27

Open zhmt opened 4 years ago

zhmt commented 4 years ago

The order of OnDestroy is not guaranteed, because the order of script excution doesn't work when calling OnDestroy.

class OneObj : MonoBehavior {
  void OnDestroy() { NativeApi.test(); }
}

The code above will raise IndexOutofBoundException randomly when stopping game in editor.

I dont know how to solve this problem.

I am using a stupid solution:

  1. invoke DllManipulatorScript.Reinitialize in Awake(){} when game started.
  2. manually invoke DllManipulatorScript.Reset via menu item before building cpp dll.

Is there better way?

zhmt commented 4 years ago

How about initializing dll when game started, and reset befor DllManipulatorScript's destructor is called?

If My NativeApi object hold an refercence of DllManipulatorScript , it will stop DllManipulatorScript being GCed before all my GameObjects are destoryed.

zhmt commented 4 years ago

Something like this:

class DllManipulatorScript {
  void Awake() { Reinitialize(); }
  ~DllManipulatorScript () { Reset(); }
}

class MyNative {
  object dllScriptRef;
  Awake() { dllScriptRef = GameObject.Find("DllManipulatorScript"); } 

  [DllImport]
  static extern void test();
}
mcpiroman commented 4 years ago

The problem is, at least when I last tested it, destructor is not called in editor when you just stop the game (or maybe only when it's the selected object in the scene, something of that nature). But if it turns out I'm wrong about that and it's gonna work fine, then yeah, I can change that.

zhmt commented 4 years ago

I tested, you are right. It is pretty tough to clean up at right time.

zhmt commented 4 years ago

Luckly, mannally dll unloading works fine.