Search code examples
unity-game-enginegame-physics2d-gamesunity3d-2dtools

3D Classes in a 2D Unity Game


I have a lot of Unity scripts written for a 3D game that would be useful in a 2D game, and I really don't want to reinvent the wheel to add them to that game. So my question is, can I use my current 3D game scripts (with Vector3s and calls to Physics.Raycast(), Physics.Gravity, etc.) in a 2D game (where all the GameObjects have 2D components like Collider2D and Rigidbody2D and there will be other scripts using calls to Physics2D.Raycast(), Physics2D.Gravity, etc.)? I'm guessing that I can do it but that it will be stupid inefficient, so I might as well re-implement with 2D classes. But figured I'd ask first.

Thanks for your help!


Solution

  • Just like the comment from Joe, you can. There will be no problem since the Unity 2D functions will takes vector2D and when Vector3D is passed into them, z axis will be discarded.

    My suggestion is to use the-same Script for 3D and 2D as that makes everything easier to work with. For example, when you make big game logic changes in your 3D script, you have to do the-same in 2D script. Also a big pain when you want to troubleshoot your 2D or 3D codes. This is where C# Preprocessor Directives should be used.

    #if USE2D
    //Put your 2D specific API code
    #else
    //Put your 3D specific API code
    #endif
    

    Now, to test 2D code, simply put #define USE2D at the top of your code. This can be helpful when you want to troubleshoot your 3D and 2D codes. You just comment #define USE2D to test 3D code and uncomment it to test 2D code.