Как перенести проект unity на другой компьютер
Перейти к содержимому

Как перенести проект unity на другой компьютер

  • автор:

Очистка и перенос существующего проекта Unity на новый тот или иной компьютер

Я хочу скопировать свой существующий проект Unity в новый пустой проект Unity. Похоже, что все ссылки на объекты и многие сценарии не настроены должным образом / не присутствуют в Иерархии в моих сценах.

Я только скопировал папку с ресурсами / package.json в новый проект Unity, потому что остальные файлы грязные и кэшировали много бесполезной информации.

Где находятся файлы с подробными данными о сценах? Я хочу скопировать это, чтобы я мог запускать свои сцены со всеми ссылками на объекты и сценариями, установленными на правильные игровые объекты.

2 ответа

Перед запуском всегда делайте резервные копии — мало ли!

Убираться

Как правило, вам всегда понадобятся папки Assets , ProjectSettings и Packages .

Все остальное вы можете удалить, и Unity воссоздаст / перекомпилирует их, когда вы снова откроете проект.

Также см. За кулисами (более новые версии Unity см. в Использование внешнего контроля версий вместо этого)

При резервном копировании проекта или добавлении проекта в репозиторий контроля версий вы должны включить основную папку проекта Unity, содержащую как Активы, и папки ProjectSettings и Packages. Вся информация в этих папках имеет решающее значение для работы Unity.

Как говорят имена

  • Assets — это все ваши активы, такие как сценарии, изображения, сборные конструкции и т. Д., Включая также сцены.
  • ProjectSettings — это общие настройки вашего проекта, касающиеся таких вещей, как качество, физика, струны плеера и т. Д.
  • Packages определяет, какие пакеты должны быть автоматически импортированы PackageManager ( manifest.json ), какие из них являются зависимостями, а какие даже локальными пакетами (если они есть)

Для меня некоторые файлы Library/*.asset имеют смысл сохранить. параметры сборки, целевая платформа и т. д., поэтому мне не нужно настраивать их/переключать платформу с нуля каждый раз, когда я «сбрасываю». Это зависит от вас, конечно, если вы хотите сделать это, а также.

Вы также можете использовать любую другую систему управления версиями. или, конечно, удалить соответствующие папки и файлы вручную, но я всегда использую GIT для моих проектов.

Также см. Использование внешних систем контроля версий с Unity, чтобы получить некоторую общую информацию о настройке версия, управляющая вашим проектом(ами).

Поэтому, когда я хочу очистить репозиторий, прежде чем копировать его, я обычно использую следующее как *.gitignore (это очень просто — для более полной и постоянно обновляемой версии см. тот, что на Github!).

Все, что здесь перечислено, можно в основном удалить и будет повторно скомпилировано при следующем открытии проекта в Unity. (Строки, начинающиеся с ! , являются исключениями, которые я добавил, потому что, как я сказал, имело смысл сохранить и их.)

И как сказал лично для меня иногда имеет смысл добавить

Если это еще не сделано, сначала инициализируйте запущенный репозиторий.

Это покажет некоторые предупреждения для каждого файла, который указан в .gitignore , но вы можете игнорировать эти предупреждения. Он только говорит что-то подобное, например

Вы пытаетесь добавить игнорируемый файл в коммит, и он будет пропущен

Сделать вашу первую фиксацию.

Теперь, наконец, вы можете просто запустить git clean

Который удаляет каждый файл, который не отслеживается (поэтому не забудьте всегда иметь все файлы, которые вы хотите сохранить, по крайней мере, в промежуточном состоянии ( git add ) или, лучше, сначала зафиксируйте) или будет игнорироваться *.gitignore .

Если вы не уверены, вы также можете добавить

Примечание. Если у вас уже был репозиторий .git , но впоследствии вы добавили или отредактировали .gitignore , также обратитесь к Как заставить Git «забыть» о файле, который был отслежен, но теперь находится в .gitignore?

Миграция с помощью UnityPackage

Другой вариант перемещения сцен или частей активов между двумя разными проектами — использование Пакет Unity. Обратите внимание, что это не будет включать какие-либо установленные пакеты, настройки и т. д., а только активы и их зависимости от активов (связанные префабы, материалы, текстуры и т. д.)!

Из текущего проекта экспортируйте UnityPackage

Выдержки из Документов:

  1. Откройте проект, из которого вы хотите экспортировать активы.

  2. Выберите в меню Активы → Экспорт пакета , чтобы открыть диалоговое окно «Экспорт пакета». (См. изображение диалогового окна «Экспорт пакета» ниже.)

  3. В диалоговом окне выберите ресурсы, которые вы хотите включить в пакет, установив флажки напротив них.

  4. Оставьте флажок «Включить зависимости» установленным, чтобы автоматически выбирать любые ресурсы, используемые выбранными вами.

  5. Нажмите «Экспорт», чтобы открыть проводник, и выберите, где вы хотите сохранить файл пакета.

  6. Назовите пакет и сохраните его в любом месте.

В качестве альтернативы шагу 2 вы также можете щелкнуть правой кнопкой мыши по папке Assets в Project View и найти параметр Export Package в контекстное меню.

а затем в новом проекте импортируйте UnityPackage

  1. Откройте проект, в который вы хотите импортировать активы.
  2. Выберите Активы → Импорт пакета → Пользовательский пакет .
  3. В проводнике файлов выберите нужный пакет, и появится диалоговое окно «Импорт пакета Unity» со всеми предварительно отмеченными элементами пакета, готовыми к установке. (См. Изображение диалогового окна «Импорт пакета Unity» ниже.)
  4. Выберите Import , и Unity поместит содержимое пакета в папку Assets , к которой вы можете получить доступ из вашего Project view .

В качестве альтернативы шагам 2 и 4 вы даже можете просто перетащить файл unitypackage в папку Assets через редактор Unity.

Как перенести проект unity на другой компьютер

See Asset Packages for detailed information on using packages, including importing and exporting.

Exporting New Packages

Use Export Package to create your own Custom Package.

  1. Откройте проект, в который нужно поместить ассеты.
  2. Выберите Assets->Export Package… из строки меню. (See Fig 1: Exporting Package dialog box.)
  3. In the dialog box, select the assets you want to include in the package by clicking on the boxes so they are checked.
  4. Leave the include dependencies box checked to auto-select any assets used by the ones you have selected.
  5. Click on Export to bring up File Explorer (Windows) or Finder (Mac) and choose where you want to store your package file.
  6. Присвойте пакету имя и сохраните его, где вам удобно.

HINT: When exporting a package Unity can export all dependencies as well. So, for example, if you select a Scene and export a package with all dependencies, then all models, textures and other assets that appear in the scene will be exported as well. This can be a quick way of exporting a bunch of assets without manually locating them all.

Fig 1: Exporting Package dialog boxFig 1: Exporting Package dialog box

Exporting Updated Packages

Sometimes you may want to change the contents of a package and create a newer, updated version of your asset package. To do this:

Select the asset files you want in your package (select both the unchanged ones and the new ones).

Export the files as described above in Export Package, above.

NOTE: You can re-name an updated package and Unity will recognise it as an update, so you can use incremental naming, for example: MyAssetPackageVer1, MyAssetPackageVer2.

HINT: It is not good practise to remove files from packages and then replace them with the same name: Unity will recognise them as different and possibly conflicting files and so display a warning symbol when they are imported. If you have removed a file and then decide to replace it, it is better to give it a different, but related name to the original.

How to move or copy a Unity project (without breaking it)

Move a project in Unity

When working on a project in Unity, you may want to move it to another computer or a different folder location.

Maybe you’re looking for a simple way to back up your work, or maybe you just want to work on it from different computer than you started on.

Perhaps you want to duplicate the entire project in the same location so that you can work on two versions at once…

Whatever the reason, while it is a very simple task there are a couple of tips to keep in mind that will make moving or copying a Unity project much easier.

So… what’s the best way to move a Unity project to a new location?

The right way to move or duplicate a Unity project is by copying the entire folder to the new location, making sure to enable ‘Visible Meta Files’ in the Project Settings first. It also helps to remove the Library and Temp folders when moving the project, as these can be very large and are not required, as Unity will rebuild them automatically.

This is different to exporting a Unity Package, which does not include project-wide settings and package manager dependencies. Moving a project by copying the folder is the best method for moving an entire project to a new location without breaking it.

In this article I’ll be exploring each step in detail, as well as a few tips to make moving your project a little easier.

Here’s what you’ll find on this page:

How to move a Unity Project step by step

1. Enable Visible Meta Files

Visible Meta Files Option in Unity

The Version Control option in Project Settings allows you to make hidden meta files visible. A must when using version control software.

Got to Edit > Project Settings and select the Editor Tab.

Find the Version Control Mode and, if it’s not already, set it to Visible Meta Files.

How to change the Version Control in Unity 2020 and up

In Unity 2020, you’ll find this option in the Version Control tab of the project settings, not the Editor tab.

Why should you enable Visible Meta Files in Unity?

In Unity every asset has hidden meta data that is used to make and maintain references between script variables, game objects and assets. This meta data is stored in .meta files which are created by Unity when you import assets.

These meta files are hidden by default and, while Unity does not need to be visible to use them, other software may do. Enabling Visible Meta Files simply makes sure that they are included when the project is moved or copied.

Unity Meta Files

Normally hidden, Unity’s meta files are used to maintain references between objects and assets.

This prevents the hidden references from being recreated, overwritten, or duplicated which can cause broken connections and errors. This is especially important if using version control software or when accessing the same project from multiple locations.

The good news is that, while researching for this article, I wasn’t able to deliberately break a project by keeping the meta files hidden, so it’s unlikely that missing out this step will cause you many problems in most scenarios.

As it’s such an easy step, and because it can potentially protect your entire project from breaking when you move it, it’s good practice to set them to visible anyway.

2. Delete the Library and Temp folders from the project directory (optional)

Delete Library and Temp folders in Unity

Deleting the Library and Temp folders can help to bring the size of the project down before moving it.

This step is optional and only applies if you wish to move a Unity project to a different computer.

Open File Explorer (Windows) or Finder (Mac) to find your Unity Project.

Unless you’ve changed the default location for new projects, you’ll find your project in your Documents folder under Unity Projects.

If you can’t find your project folder then open up the Unity Hub, find your project in the list and select ‘Show in Explorer’.

Once you’ve found your project folder, copy the entire directory to a new location (your desktop for example).

Open the copy and delete the Library folder and the Temp folder (if there is one) from the directory.

Why should you delete the Library and Temp folders?

You don’t have to delete these folders.

The reason that you may want to, however, is to reduce the size of the directory before you move it.

For example, to test this method I moved a small project which, when zipped, was 180 MB in size with the Library folder included.

By removing the Library folder first, it was only 25MB.

Removing the Library and Temp folders can massively reduce the size of the folder temporarily. This is ideal if you want to fit it on a small USB stick or share it online.

Then, when you open the project copy, Unity will rebuild the Library folder in the new location, restoring it to its original size.

Why make a copy of project directory first?

How to copy a Unity project to your desktop.

Copying the project to a different folder first lets you remove the unnecessary Library and Temp folders without damaging your project.

It is safe to remove the Library and Temp folders from the original project directory as Unity will simply rebuild them when you next open the project.

For the time it takes to make a copy of the project first, it’s much safer to do it this way. As deleting the wrong folder by mistake could break your project.

3. Compress the folder to a Zip file (optional)

How to Compress and move a Unity Project

Unity projects, even small ones, have thousands of files. Zipping the directory makes the project easier and quicker to move.

This step is optional. It’s most relevant if you wish to upload a Unity Project using cloud storage, such as Dropbox.

When you’re ready to move your project, it’s time to Zip the project folder.

Right Click on the root folder, which is named after your project, and select Send To > Compressed (Zipped) Folder (Windows) or Compress (Mac).

Why should you Zip the project folder first?

You don’t have to Zip the project folder to move it.

A Unity project, even a small one, may include many thousands of files.

And while this may not cause you any issues when moving a project locally, it can affect performance when uploading and downloading so many individual files. Something you may have noticed if you’ve ever created a new project (even a completely empty one) inside of a Dropbox folder.

It took 1m 33s to upload my test project which, although small, included almost 10,000 individual files.

To upload the same project when zipped, only took 40 seconds.

And while the time savings in my example are small, it’s likely that your project is much larger and much more complex.

Zipping the folder makes it easier to manage and quicker to move.

4. Copy the project folder to the new location

Moving a Unity Project to a new folder (visualisation)

Move the copied project folder to the Unity Projects folder on the target computer.

Lastly, paste the directory, or extract the zipped project folder, to the new location.

How to create a duplicate Unity Project in the same location

If you’re not moving the project to a new location, and all you want to do is create a working duplicate in the same folder as the original project, here’s how to do it.

  1. Enable Visible Meta Files but ignore steps 2 and 3.
  2. Duplicate the project folder inside the Unity Projects directory.
  3. Rename the new folder as you like.
  4. Add the new project copy to Unity Hub (see below).

5. Add the project to Unity Hub

Add a new project to the Unity Hub

Click Add to add the new location to your Unity Hub after you’ve moved it.

If you’re using Unity Hub you’ll need to add your, now moved, project to the list of Projects in your dashboard.

Simply open Unity Hub, click Add and select the new project directory.

At this point you may also want to make sure that you have the same version of Unity installed as the source project (if moving the project to a new system).

If you don’t, you can download a specific version of Unity, (including older versions) from Unity’s download archive.

You can now open the project as normal.

How to remove a project from Unity Hub

If you’re no longer using the original project you may want to remove it from the Unity Hub projects list.

To do so simply find the project from the list and select Remove from List from the dropdown menu on the right hand side.

Unity Hub- Remove Project from List

Removing a project from the Unity Hub does not delete it, but it does tidy up your list.

This will remove the project from the Unity Hub list but it will not delete the project folder.

If you want to do that, you can simply delete the project folder manually from the Unity Projects folder.

Now I want to hear from you

If you’ve been working in Unity, chances are you’ve had to move your Unity project at some point.

Were you able to move the project without breaking it?

And if something did go wrong, what do you wish you had known beforehand that would help someone else right now?

Whatever it is, let me know by leaving a comment below.

Image Attribution

  • Icons made by Freepik from www.flaticon.com
  • Unity Logo © Unity Technologies

by John Leonard French

Game audio professional and a keen amateur developer.

Get Game Development Tips, Straight to Your inbox

Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.

My favourite time-saving Unity assets

Rewired (the best input management system)

Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.

DOTween Pro (should be built into Unity)

An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.

Easy Save (there’s no reason not to use it)

Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.

Comments

Thanks a lot ive been working hard on a project and got a new laptop. ive been stuck trying to figure out how to move my project from my old pc to my new laptop. I followed your instructions and I was able to open it without any crashes or bugs, Thanks A LOT

But about keystore for unity android project. I need backup it

Thanks, very helpful.

I just transferred my project this way and the only issues that came up was the Editor layout doesn’t transfer (tied to Unity install, not project), and the Snap & Grid settings fall under that.

Obviously it only takes a few seconds to reset your layout, but in case you have a very precise setup you can use Window > Layouts > Save to file… to transfer that too.

Snap & Grid settings are very important for my project, as it is 2D Pixel-based. Very glad I noticed that had changed before moving/importing any sprites.

Great tip, thank you!

Thank you — very clear and helpful!

Didn’t work for me. When I moved the whole folder (without deleting anything) the project won’t load. I get a weird half transparent view of the Steam holding room with my project also half visible but I’m in the wrong place and not able to interact with anything… Have tried it a few times now. I wanted to make a copy to experiment with so I can preserve the work I have done so far so this is a bit frustrating. Can’t think why it doesn’t work. I have to add it to Unity hub and open it that way – dont know how else to do it so maybe that’s causing the problem.

I’d double-check the basics, i.e. make sure you’re using the same version of Unity, that you have any package manager dependencies installed in the new project (this should happen automatically) and that no files have been left out during the transfer. Beyond that, I’d need to know your project better to be able to help. If you don’t mind sharing details about it you can email me at [email protected]

It all worked for a regular project, although how about when copying a cloud collaborated project? I have found that when I copy the project folder, it still retains relationships to the cloud in the original. How can I detach it cleanly from the original cloud?

Hi Jesse, I might be able to update this article to include managing Cloud projects in the future but, for now, I’d recommend getting in touch with Unity on that one.

Very useful thank you!
One thing that happened to me as I was working on a scene and then I wanted to open a new scene, thinking it was a “new project”. So Unity doesn’t work that way…and it cleaner my previous project (luckily only testing map and playing around).

That’s why I was looking for an article like this to create a physical backup somewhere as well. Thanks for the tips!

Thanks for this well put article.

My project is in my OneDrive folder. I regularly make a copy of the entire project on my F drive for backups. When I open one backup from UnityHub, I find many occurrences of the OneDrive path in files like *.csproj. So I guess it is why when I open a script by clicking inside Unity log console, I get the OneDrive version and not the copied version. Why the paths are not updated? – ‘Visible Meta Files’ is enabled but I do not delete Library and Temp folders.

That’s interesting. Does this happen only when clicking from the log console? i.e. not an actual script file in the project panel.

Yes.It does not happen when 2x clicking a script from the project panel. I did not notice this before your question – thanks. I tried with a deleted library folder but the project becomes corrupted with 100s of errors. So I guess something is wrong with my project or something is missing in the copy procedure. Have you tried on your side to open, from a copied project, a script from the stack trace in the console?

I haven’t tried that but I’ll look into it. If I can recreate it and find a cause I’ll update the article with the extra info.

Thank you for your help. I was having issues as my project was initially saved on the usb to save storage space. The problem is, the usb was getting so hot that it ended up dropping-off in the middle of running Unity. Transfered it to a new location and it was running with no issues ��

Probably a good idea! I’ve found this to be the case when syncing a project with Dropbox too, where syncing the project can cause high CPU usage.

Thank you so much! Now making game backups is more convenient and less space. ^_^ This saves me a lot of back up on my works…

You’re welcome, great to hear it helped you!

I have a problem that when I open the project on the new computer it stuck on “resolve packages” loading screen and never open it, I tried over and over but it doesn’t work, and It’s very important project for me and I can’t find a way to resolve it, please help!

I don’t have any experience with that error, but after some searching, it seems to be a package manager issue (I assume it’s trying to check and download any packages that you need). This forum post might be helpful: https://forum.unity.com/threads/stuck-on-resolving-packages.544269/ alternatively, official support may be the way to go on this one.

Very, Simple, Very Concise, and, Easy to follow. Thank You!

The most comprehensive move instructions on tinternet, thanks!

Very clear and reassuring – instills the confidence to try and it is a revelation to see how compact a project is without the Library.

I did not see the option to show/hide the Meta files – perhaps this has gone in the latest version of Unity? – but they were in the directories, perhaps by default.

Would Echo the previous poster who enquired about doing this that is already under Collaborate. Would be good to know what safe options exist for severing (or keeping) those links.

I’ve used the collaborate feature before and found it to be, surprisingly, very easy (particularly for cloud storage and working on the same project on multiple computers). I haven’t thoroughly tested it with a large project yet, hopefully I can write a future article on it.

I would love to see an article on the built-in Collaborate feature. Thanks for all the great content!

You’re welcome. I’ve used it briefly and found it surprisingly easy, I’d like to do an in-depth article on it some time in the future. It’s on my list!

You sincerely saved my soul with this one. Thanks.

Hi, I’ve just been wondering if you can import your Unity project to mac? I’ve been thinking about switching to a mac and I don’t want to lose all my Unity projects.

I’m not aware of any major issues switching between platforms, although you’ll see an advisory message in the console about script line endings. You may want to also make sure your target platform matches too. So it’s probably a good idea to make a backup but I’ve recently used both PC and Mac on the same project (via Unity Cloud) and it’s been working fine.

I was recently needing to do this so as to be able to switch between making small tweaks on the stable version while developing completely new behaviours on the other. I would recommend to anyone doing this to delete the .sln and .csproj files along with the Library and temp folders because intellisense stopped working on vs code for me and this is because the files will point to the previous project. I just pushed my stable project to github with .gitignore ignoring the usual files and folders and then I cloned it to a new project and Unity rebuilds everything when the project opens.

Thanks for the tip!

Github, or BitBucket, is a MUCH better way to do this, worthy of a whole article by itself. In addition to being able to move a project, you get built-in archiving and easy undo.

For example, 2020.2 is finally out. Push your project to github, then create a branch to work on the upgrade (or a bug, whatever). Once everything works, then merge it back into the main branch. If it doesn´t, simply revert.

I develop on a desktop most of the time, but a laptop when I travel, so this is critical for me.

Thanks Tac, for your feedback. Personally, I really like the built-in Collaborate feature for saving a project to the cloud, but I’m not a professional developer, and I accept that Github and options like it can offer much more, certainly at scale, if you’re comfortable with using them. It really depends on what you need from it. Thanks again.

I would love to see an article on the built-in Collaborate feature. Thanks for all the great content!

Hey John. I recently purchased some apps to reskin but I am a complete noob on this front. I have watched videos and tutorials on how to work inside of unity but have found no solid info on how to import the source code that I purchased. I ended up changing my file name to .unitypackage and got it into Unity but all I can see is the game and the info in the Projects folder. Everything appears to be there but when I click on Scene to look at the programming, it’s just a 3D view of the background like there’s nothing there. Not sure what I did wrong but can’t figure out how to get the project loaded to make my reskin changes. I am very new and very confused but anxious to get started on this process. Been studying for 2 months before even attempting and now……I am stuck. Thanks for any advise you have for me.

Hi Patsy, if it’s fair to say that you’re fairly new to using Unity? it’s going to be hard to tell if there’s an issue with what you have, or if you’re just unfamiliar with how to work with it. Best advice I can give is to get someone with a bit more experience with Unity to take a look at it, if only to double-check that you’re not missing something basic. Hope that helps.

Thank you sooooo much Sir!

Thanks for the instructions; I’m new to Unity (just finished Brackeys ‘How to make a Video Game in Unity’ tutorial) and always good to know, how to duplicate a project safely in this environment.

Just two small remarks:
1) in Unity 2020.3.0 (possibly earlier), the single ‘Mode’ option for version control has been moved from ‘Editor’ to ‘Version Control’ menu, so now it’s better to write: ‘Got to Edit > Project Settings and select the Version Control Tab.’. The attached screenshot need to be updated as well.

2) in my case, the Mode is already on ‘Visible Meta Files’ and I can see the .meta files under Assets, as expected.
I’m not sure though, wether this is now the default setting, or Brackeys made me change that during his course…

Thanks for the tip, I’ll take a look at how this works in 2020 and see about updating the article.

Good explanation! Very didatic! Thanks!

Glad you liked it!

This worked for the most part. But two things seem to happen no matter what I do. First, my main character script is not linked, and all the audio sources are missing their audio files (but the audio files are still in the assets). This happens no matter what I do, no matter which project I copy over.

Thanks for your feedback Robert. I don’t know what’s causing this for you. There seems to have been some issues with missing references in rare circumstances (see this forum thread for more) however this may not apply to your project. Could you let me know your Unity version so I can look into it when updating this article in the future?

Thanks, John! Just moved my project from Mac to Windows. The project was already using Git so I thought I was safe, but when I opened the project on Windows, all of the script links were broken. Turns out the meta files weren’t there because, while I had meta files visible, they were ignored in my .gitignore. I think I had combined a standard Unity .gitignore with a .NET .gitignore, so beware of .gitignore leaving your files behind!

Just posting this here in case someone else moves a git project. ��

Thanks for the heads up, hopefully, you’ve saved someone else from having the same issue.

Great article, thank you.
You don’t cover the case where you want to duplicate a project and rename it.

How to proceed ? Is the .sln file the only one to rename ? This is the only one where I see a link to the main project parent folder name.

If you duplicate the project folder, then add it to Unity Hub as a different project and open it, any scripts you open from that project should be part of the new project and a new Visual Studio Solution, without you having to manually rename the .sln (in the test I ran a new .sln was created). However, others have reported different results and others have recommended removing the sln, so your mileage may vary. I’ll update this article in the future with an expanded section on duplicating projects and how it affects Visual Studio.

I’m partly working in an offline environment and have problems opening projects that depend on packages like [email protected] or [email protected]
How can i move these files with my projects and where do i have to copy them into?

I copied the folders from my internet connected machine that have all the packages from AppData\Local\Unity\Cache\packages.unity.com\ and tried to put them into the same folder on my offline-device but unity didnt recognized them and said missing dependencies.
Then i tried putting them directly into the PackagesCache folder inside “Library”, but whenever i opened the project in unity, unity automatically deleted the additional folder i put into.

I haven’t done any offline testing with Package Manager dependencies. My only understanding of this is that, depending on your Unity version, it may not be properly supported at all and that the easiest way to move Packages is to let Unity manage the dependencies online. See this Unity forum thread for more information.

Thanks a lot for the thorough well-made explanation!

Hi John, thanks for the article. Anyone struggling with Collaborate after duplicating the project where new project still pointing at old project can do following to resolve the issue.

1. Go to Edit >> Project Settings >> Services (General Settings panel on the right)
2. We need to Unlink existing Project ID & create new one. For this, in general settings, look for Unity Project ID & click on “Unlink Project” button.
3. Then, select your organization and create a new Project ID.

This should decouple the new project & you should have clean collaborate repository.

Hope this helps someone ��

Thanks for the tip Rupesh!

recently i moved my project (so unity could run it more efficiently) from a solid state external hard drive by only moving the assets and project settings folders but it didn’t seem to help much speed wise…
after opening the project through the unity hub it was able to rebuild it pretty well but had i known, i would have brought the package folder with it because i had to reinstall all the packages that were previously installed.
what benefits would i achieve by including the logs folder, if any?

That helps me alot because i didnt know that Library and tamp folder can be deleted without problem but i know faster solution for zipping. Just go to your folder, select everything, diselect Library and Temp folder then click RMB – 7zip – add to archive. Change name and voala you dont need to copy entire project first

Great tip! Thank you.

Hey John, you have helped me a lot, it worked out perfectly. You have my deepest gatitude man. Keep up the good work!

I’ve been working on a very large project that (along with everything else on my computer) outgrew my 110 Gig hard-drive and I didn’t catch on until I was in the middle of a build. Then it was 2 days of nauseating stress wondering what to do, chasing down error messages. I learned that disk space was likely the cause, and I rediscovered the 900 Gig D: drive that’s been on my computer the whole time that I never really noticed. I think it’s an SSD built in add-on.

Anyway, it was my last hope, and I found your tutorial, and it brought order back into my life in the time it took to follow these very, very thoughtful, flawless directions. Thank you, thank you, thank you.

Well done for getting that sorted! I’m so glad my article helped you.

Leave a Comment Cancel reply

Welcome to my blog

John Leonard French - Photo

I’m John, a professional game composer and audio designer. I’m also a keen amateur developer and love learning how to make games. More about me

Latest Posts
  • Addressable Assets in Unity
  • Async in Unity (better or worse than coroutines?)
  • State Machines in Unity (how and when to use them)
  • How to use Arrays in Unity
  • How to delay a function in Unity
Thanks for Your Support

Some of my posts include affiliate links, meaning I may earn a commission on purchases you make, at no cost to you, which supports my blog.

Миграция хоста

В многопользовательской сетевой игре без выделенного сервера один из экземпляров игры выступает в роли хоста — центра управления игрой. Это игрок, чья игра выступает в роли сервера и «локального клиента», в то время как каждый из других игроков запускает «удаленный клиент». Дополнительную информацию см. в документации по концепциям сетевой системы.

Если хост отключится от игры, продолжение игры будет невозможно. Распространенными причинами отключения хоста являются уход игрока хоста, сбой хост-процесса, отключение компьютера хоста или потеря хостом сетевого подключения.

Функция переноса хоста позволяет одному из удаленных клиентов стать новым хостом, чтобы можно было продолжить многопользовательскую игру.

Как это работает

Во время многопользовательской игры с включенной миграцией узла Unity распределяет адреса всех одноранговых узлов (игроков, включая хост и всех клиентов) всем другим одноранговым узлам в игре. Когда хост отключается, один узел становится новым хостом. Затем другие узлы подключаются к новому хосту, и игра продолжается.

Компонент Network Migration Manager использует Unity Networking HLAPI. Это позволяет продолжить игру с новым хостом после отключения исходного хоста. На приведенном ниже снимке экрана показано состояние миграции, отображаемое в Network Migration Manager в Inspector окне Unity, в котором отображается информация о текущем выбранном GameObject, активы или настройки проекта, позволяющие просматривать и редактировать значения. Дополнительная информация
См. в окне Словарь .

Компонент «Диспетчер миграции сети»Компонент «Диспетчер миграции сети»

Диспетчер миграции сети предоставляет базовый пользовательский интерфейс, похожий на HUD диспетчера сети. Этот пользовательский интерфейс предназначен для тестирования и прототипирования во время разработки игры; прежде чем выпустить игру, вы должны внедрить собственный пользовательский интерфейс для переноса хоста и пользовательскую логику для таких действий, как автоматический выбор нового хоста без ввода данных пользователем.

Network Migration Manager прототипирует HUDNetwork Migration Manager прототипирует HUD

Несмотря на то, что миграция могла произойти из-за того, что старый хост потерял соединение или вышел из игры, старый хост игры может снова присоединиться к игре в качестве клиента на новом хосте.

Во время переноса узла Unity поддерживает состояние SyncVars и Списки синхронизации во всех сетевых GameObjects Фундаментальный объект в сценах Unity, который может представлять персонажей, реквизит, декорации. , камеры, путевые точки и многое другое. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
См. в Словарь в Сцена Сцена содержит окружение и меню вашей игры. Думайте о каждом уникальном файле сцены как об уникальном уровне. В каждой сцене вы размещаете свое окружение, препятствия и декорации, по сути проектируя и создавая свою игру по частям. Подробнее
См. в Словарь . Это также относится к пользовательским сериализованным данным для GameObjects.

Unity отключает все игровые объекты игрока в игре, когда хост отключается. Затем, когда другие клиенты снова присоединяются к новой игре на новом хосте, соответствующий модуль игроков повторно включает этих клиентов на новом хосте и повторно порождает их на других клиентах. Это гарантирует, что Unity не потеряет данные о состоянии игрока во время переноса хоста.

ПРИМЕЧАНИЕ. Во время переноса хоста Unity сохраняет только те данные, которые доступны клиентам. Если данные есть только на сервере, то они недоступны клиенту, который становится новым хостом. Данные на хосте доступны только после переноса хоста, если они находятся в SyncVars или SyncList.

Когда клиент становится новым хостом, Unity вызывает функцию обратного вызова OnStartServer для всех сетевых игровых объектов. На новом хосте Network Migration Manager использует функцию BecomeNewHost для создания сетевой сцены сервера из состояния текущего ClientScene.

В игре с включенной миграцией узла узлы идентифицируются по их connectionId на сервере. Когда клиент повторно подключается к новому хосту игры, Unity передает этот идентификатор соединения новому хосту, чтобы он мог сопоставить этого клиента с клиентом, который был подключен к старому хосту. Этот идентификатор указан в ClientScene как reconnectId.

Игровые объекты, не являющиеся игроками

Игровые объекты, не являющиеся игроками, с правами доступа клиента также обрабатываются миграцией хоста. Unity отключает и повторно включает неигровые игровые объекты, принадлежащие клиенту, точно так же, как она отключает и повторно включает игровые объекты игрока.

Идентификация пиров

Перед тем, как хост отключится, все одноранговые узлы будут подключены к хосту. Каждый из них имеет уникальный идентификатор подключения на хосте — в контексте переноса хоста он называется oldConnectionId.

Когда Network Migration Manager выбирает новый хост и одноранговые узлы повторно подключаются к нему, они предоставляют свой oldConnectionId , чтобы определить, к какому из одноранговых узлов они относятся. Это позволяет новому хосту сопоставить этого повторно подключающегося клиента с соответствующим игровым объектом игрока.

Старый хост использует специальный oldConnectionId , равный нулю, для повторного подключения. Поскольку у него не было подключения к старому хосту, он БЫЛ старым хостом. Для этого существует константа ClientScene.ReconnectIdHost.

При использовании встроенного пользовательского интерфейса Network Migration Manager Network Migration Manager автоматически устанавливает oldConnectionId . Чтобы установить его вручную, используйте NetworkMigrationManager.Reset или ClientScene. SetReconnectId.

Процедура переноса хоста

На MachineA размещена игра Game1, для которой включен перенос хоста

Компьютер B запускает клиент и присоединяется к Game1

  • Компьютеру B сообщается об одноранговых узлах (MachineA–0 и о себе (MachineB)–1)

MachineC запускает клиент и присоединяется к Game1

  • MachineC сообщается об одноранговых узлах (MachineA–0, MachineB–1 и о себе (MachineC)–2)

Компьютер A разрывает соединение в игре 1, поэтому хост отключается

Компьютер B отключается от хоста

Функция обратного вызова MachineB вызывается в MigrationManager на клиенте

Игровые объекты MachineB player для всех игроков отключены

MachineB остается в онлайн-сцене

MachineB использует служебную функцию для выбора нового хоста, выбирает себя

MachineB вызывает BecomeNewHost()

MachineB начинает слушать

Игровой объект игрока MachineB для себя повторно активирован

MachineB Игрок для MachineB вернулся в игру со всем своим старым состоянием

MachineC отключается от хоста

Функция обратного вызова MachineC вызывается в MigrationManager на клиенте

Игровые объекты MachineC player для всех игроков отключены

MachineC остается в онлайн-сцене

MachineC использует служебную функцию для выбора нового хоста, выбирает MachineB

  • MachineC повторно подключается к новому хосту.

Компьютер B получает соединение от MachineC

MachineC отправляет сообщение о повторном подключении с oldConnectionId (вместо сообщения AddPlayer)

функция обратного вызова вызывается в MigrationManager на сервере

MachineB использует oldConnectionId для поиска отключенного игрового объекта игрока для этого игрока и повторно добавляет его с помощью ReconnectPlayerForConnection()

Игровой объект игрока повторно создается для MachineC

Проигрыватель для MachineC вернулся в игру со всем своим старым состоянием

MachineA восстанавливается (старый хост)

Компьютер A использует служебную функцию для выбора нового хоста, выбирает компьютер B

Компьютер A «повторно подключается» к MachineB

Компьютер B получает соединение от компьютера A

MachineA отправляет сообщение о повторном подключении с идентификатором oldConnectionId, равным нулю

функция обратного вызова вызывается в MigrationManager на сервере (MachineB)

MachineB использует oldConnectionId для поиска отключенного игрового объекта игрока для этого игрока и повторно добавляет его с помощью ReconnectPlayerForConnection()

Игровой объект игрока повторно создается для MachineA

Проигрыватель для MachineA вернулся в игру со всем своим старым состоянием

Функции обратного вызова

Функции обратного вызова в NetworkHostMigrationManager:

// called on client after the connection to host is lost. controls whether to switch Scenes protected virtual void OnClientDisconnectedFromHost( NetworkConnection conn, out SceneChangeOption sceneChange) // called on host after the host is lost. host MUST change Scenes protected virtual void OnServerHostShutdown() // called on new host (server) when a client from the old host re-connects a player protected virtual void OnServerReconnectPlayer( NetworkConnection newConnection, GameObject oldPlayer, int oldConnectionId, short playerControllerId) // called on new host (server) when a client from the old host re-connects a player protected virtual void OnServerReconnectPlayer( NetworkConnection newConnection, GameObject oldPlayer, int oldConnectionId, short playerControllerId, NetworkReader extraMessageReader) // called on new host (server) when a client from the old host re-connects a non-player GameObject protected virtual void OnServerReconnectObject( NetworkConnection newConnection, GameObject oldObject, int oldConnectionId) // called on both host and client when the set of peers is updated protected virtual void OnPeersUpdated( PeerListMessage peers) // utility function called by the default UI on client after connection to host was lost, to pick a new host. public virtual bool FindNewHost( out NetworkSystem.PeerInfoMessage newHostInfo, out bool youAreNewHost) // called when the authority of a non-player GameObject changes protected virtual void OnAuthorityUpdated( GameObject go, int connectionId, bool authorityState)

Ограничения

Чтобы миграция хоста работала правильно, вам нужно перейти к Диспетчеру сети Сетевому компоненту GameObject, который управляет состоянием сети. проекта. Подробнее
Просмотреть в компоненте Словарь и включить Автоматическое создание проигрывателя . Данные, которые присутствуют только на сервере (узле), теряются при отключении узла. Чтобы игры могли корректно выполнять миграцию хоста, важные данные должны передаваться клиентам, а не храниться тайно на сервере.

Это работает для игр с прямым подключением. Чтобы это работало с механизмом сопоставления и сервером ретрансляции, требуется дополнительная работа.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *