简体   繁体   English

在Unity和C#中跨项目重用函数

[英]re-using functions across projects in Unity and C#

I'm quite new to C# and Unity so have mercy on me. 我对C#和Unity相当陌生,所以请怜悯我。 I'm using visual studio. 我正在使用Visual Studio。

I have what seems like a pretty common problem. 我有一个看起来很普遍的问题。 Which is - i want to use functions i write across several projects in unity. 这是-我想使用我在多个项目中统一编写的函数。 I don't want to have to go search for the code in some folder, copy paste it into the new project, or fiddle with symbolic links or use .dll's. 我不想去某个文件夹中搜索代码,将其复制粘贴到新项目中,或者摆弄符号链接或使用.dll。 These are all not great solutions to the problem. 这些都不是解决问题的好方法。 Can't i just somehow create a class I can access across all my projects? 我是否能以某种方式创建可以在所有项目中访问的类? Custom namespace perhaps that is not project specific? 自定义名称空间可能不是特定于项目的? that i can simply just call at the beginning of wherever i want to use my homemade scripts. 我可以只在我想使用自己的自制脚本的任何地方开始时调用。

If you don't want to build a custom DLL and the headache that comes with maintaining its versioning alongside Unity releases, consider building an AssetPackage . 如果您不想构建自定义DLL,并且不想随Unity发行版一起维护其版本而感到头痛,请考虑构建AssetPackage You can right-click in one of your projects and export a bunch of scripts that you want to be re-used in other places together as a package. 您可以在一个项目中单击鼠标右键,然后将要在其他地方重用的一堆脚本作为一个包导出。 When you start a new project, just load that package into it by dragging and dropping it. 当您开始一个新项目时,只需将其拖放到该项目中即可。

You have 2-3 things to consider in this situation: 在这种情况下,您需要考虑2-3件事:

  • Ease of deployment 易于部署
  • Whether or not you will update that code 是否更新该代码
  • Ease of update, if you will update it 易于更新(如果要更新)

If you just want to bring it in once, then Erik's answer should be simple enough. 如果您只想将其放入,那么Erik的答案应该足够简单。
If you want to keep things as an updated library though, you will need another method. 但是,如果要将事物保留为更新的库,则将需要另一种方法。

Symbolic links as you mentioned would be the best, or DLLs. 您提到的符号链接将是最好的DLL。 However, with this, you'd run the risk of breaking your other projects if you ever modify the common lib from inside your project. 但是,如果您从项目内部修改了公共库,就有可能破坏其他项目。

Another option would be to have a separate VCS (git, svn, etc) inside your project for your common code. 另一种选择是在您的项目中为您的通用代码提供单独的VCS(git,svn等)。 This way you can update if/when you want, you can roll-back if something breaks, and you can even fork your "common" code to make a project specific change. 这样,您可以在需要时进行更新,如果出现问题可以回滚,甚至可以派生“通用”代码来进行项目特定的更改。


Since OP mentioned it, in this case, OP could specifically use Git Submodules or simply add a second Git project and add that sub-Git to the parent's .gitignore file 由于OP提到了它,因此在这种情况下,OP可以专门使用Git子模块 ,也可以简单地添加第二个Git项目并将该子Git添加到父级的.gitignore文件中。

如果将git用于项目,则可以将共享代码添加到单独的存储库中,并将它们作为git子模块添加到项目中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM