[Tutorial] Setup Git in a Unity project

Follow these steps in order to set up a Unity project with an online git repo on GitHub using a personal access token (PAT). Please share any recommendations or errors you notice and I’ll update these instructions.

GitHub

  1. Create an empty repo in GitHub including the Unity .gitignore
  2. Click User icon in top right > Settings > Developer Settings > Personal Access Tokens > Fine-grained tokens > Generate New Token
  3. Toggle on permissions. Include at least “Contents” with read and write permission.
  4. Copy paste token contents somewhere safe. You can’t see the token after you close it. If you lose it you can create a new one.

Unity

  1. In Unity Hub, create a Unity Project with the exact same name as the GitHub repo
    a. If you already have a project created, then skip this step

  2. Close the project

  3. Rename the project so it doesn’t conflict when we clone the repo from GitHub. An easy choice is to simply add an underscore to the beginning of the project name. e.g. “_MyProject”. The reason we first named it the same is simply so that you don’t have to relocate it in the Unity Hub later.

  4. Open terminal at the project’s parent folder (the grandparent of the Assets folder)

  5. Check if you have git installed. Command: git version
    a. If that logged an error like “git is not a recognized command” then you need to install git here Git - Downloads
    b. If you already tried installing it and still get that error, copy paste the error message into google for help. Your computer may not know where to find it in your file system.

  6. Clone the repo from GitHub. Command: git clone https://<personal_access_token>@github.com/<GitHub_username>/<GitHub_repo_name>.git

  7. Move all contents of the Unity project into the newly cloned git repo folder. Then you can delete the old, empty unity project folder

  8. Move terminal to the newly cloned git repo folder. Alternatively you can simply close terminal and re-open it at the new folder. Command: cd <repo_name>

  9. Double check that it’s a valid git repo. Command: git status

  10. Double check you have a .gitignore file with the standard Unity stuff before you track all files. This should have been included in step 1 above. See gitignore/Unity.gitignore at main · github/gitignore · GitHub for the standard .gitignore if you need it.

  11. Track all existing files. Command: git add .

  12. Commit tracked files. Command: git commit -m “Initial commit.”

  13. Push the commit to GitHub. Command: git push

  14. Refresh the page on GitHub to see your files there with the “Initial commit” message.

Notes:

  • The GitHub section should work for other sites like GitLab but you’ll need to modify the instructions a bit and change the clone url
  • In the git commands above, angle brackets and their contents must be replaced with your data e.g. if you’re repo is named “MyRepo” then ‘cd <repo_name>’ would be ‘cd MyRepo’
  • You can do this process in a git GUI such as GitHub Desktop or Sourcetree. But I personally like using the command line.
  • Git has a confusing credentials/password pipeline with several options to verify your identity. These directions use the personal access token method.
  • There is a “chicken or the egg” dilemma here. Unity Hub won’t create a project in a folder that already exists and git won’t clone into a folder that already exists. These directions solve this by cloning the git repo into a new folder and simply moving the Unity project contents into that folder.
  • There is a way to connect an existing git repo and an existing Unity project without moving files by using the git push –set-upstream command, though this tends to work best if the remote repo is completely empty. I find the cloning method a bit easier.
  • Thanks to everyone in the comments for great suggestions.
5 Likes

Good stuff… it’s a learning curve well worth climbing.

You should strive to use source control as confidently as you use your file/folder system.

Here are my own notes on the process.

PROPERLY CONFIGURING AND USING ENTERPRISE SOURCE CONTROL

Please consider using proper industrial-grade enterprise-qualified source control in order to guard and protect your hard-earned work.

Personally I use git (completely outside of Unity) because it is free and there are tons of tutorials out there to help you set it up as well as free places to host your repo (BitBucket, Github, Gitlab, etc.).

You can also push git repositories to other drives: thumb drives, USB drives, network drives, etc., effectively putting a complete copy of the repository there.

As far as configuring Unity to play nice with git, keep this in mind:

I usually make a separate repository for each game, but I have some repositories with a bunch of smaller test games.

Here is how I use git in one of my games, Jetpack Kurt:

Using fine-grained source control as you work to refine your engineering:

Share/Sharing source code between projects:

Setting up an appropriate .gitignore file for Unity3D:

Generally the ONLY folders you should ever source control are:

Assets/
ProjectSettings/
Packages/

NEVER source control Library/ or Temp/ or Logs/
NEVER source control anything from Visual Studio (.vs, .csproj, none of that noise)

Setting git up with Unity (includes above .gitignore concepts):

It is only simple economics that you must expend as much effort into backing it up as you feel the work is worth in the first place. Digital storage is so unbelievably cheap today that you can buy gigabytes of flash drive storage for about the price of a cup of coffee. It’s simply ridiculous not to back up.

If you plan on joining the software industry, you will be required and expected to know how to use source control.

Source control does require learning, but there are TONS of tutorials and courses and online reference.

“Use source control or you will be really sad sooner or later.” - StarManta on the Unity3D forum boards

4 Likes

Thanks Kurt, great notes there!

1 Like

Kudos to making such a tutorial, but I’m afraid you’ve been doing it completely upside down with dozens of unnecessary extra steps and potential complications. The basics are:

  1. Create GitHub repo (WITH .gitignore for Unity)
  2. git clone <url to repo>
  3. move Unity project files into cloned git folder

In essence that’s all you need to do! :wink:

My mileage may vary slightly because I don’t use the git command line tools. I would recommend to either use GitHub Desktop or SourceTree, both are free. These may automatically perform extra steps that are super awkward to do on the command line, such as setting the upstream with an access token - I just have that set up in the Source Tree GUI once and it’ll use my token … or SSH .. whatever it is, it’s something I absolutely don’t bother with anymore after the initial install of git/SourceTree and the GitHub credentials.

The “no .gitignore” is bad advice! ALWAYS add the default “Unity” .gitignore!

Otherwise the risk is too high that one will forget about excluding the folders that mustn’t be submitted: Library, Obj, Temp, Builds, Logs, as well as the .csproj and .sln in the root. And many more.

I don’t see why including files in the initial repo would “cause trouble”.

Steps 2-4 are completely optional. I never do any of these. Maybe those relate to GitHub’s warning about forks that could take over the project? If so, fixing it at that point is sound but most important for public repos.


The main issue you will be facing creating a git repo is kind of like the “chicken and egg” problem:

  • Hub won’t create a project in a folder that already exists
  • git won’t clone into a folder that already exists

:thinking:

So what I do to ‘fix’ this is:

  • Create a new Unity project using its intended name ie “Test123”
  • Close the Unity project
  • Renamed the folder to “_Test123”

Then:

  • Create a github repo and clone it into “Test123”
  • Copy the contents of “_Test123” to “Test123”
  • then delete the (now empty) “_Test123” folder

Actually while the Unity project opens, I parallel-process creating the GitHub repo. Usually when I have the GitHub repo settings and click Create the Unity project has already finished loading.

These steps could be automated but they are so quick to do I wouldn’t mind doing it manually once a week. One could also create the Unity project with the “wrong” name initially but I think this carries over to at least Project Settings / Player / Project Name. Though most of the times we’ll change that eventually anyway.

No need to make sure because it’s the default and there’s nothing that changes that when creating new project.

Everything from here on in would be far easier if you would simply clone the github repo! There’s no need to do “git init” and over a dozen more steps when you already have a repo that you can simply git clone <url>.

These steps you can wholly discard when you just clone with a proper .gitignore (and readme etc) already existing:

  • creating the github token
  • git init
  • git status
  • git branch
  • create .gitignore
  • copy/paste .gitignore contents
  • git add .
  • git commit
  • git push with token

Then move the Unity files in that folder and be done with it.

NO! Don’t ever exclude the Packages folder!

Packages contains the manifest.json which is absolutely essential to make the project function when pulled elsewhere. It works initially but as soon as you add or remove or update a package or the editor version of the project, the missing manifest.json is almost certainly going to lead to problems with remote projects due to extra or missing packages, or packages with incorrect versions.

Packages may also contain “embedded” packages ie Packages that are moved into the project’s repository. This can be done to avoid having to separately pull packages, or to guarantee a specific version of the package being used by the project, or just to simplify setup as embedded packages already exist in the project and don’t need to be added manually (you would have to do so for git or “from disk” packages).

I repeat: /Packages MUST NOT be ignored!

I wouldn’t recommend ignoring Assets/Samples either. This should be left to users making that decision when the time comes because one might reference assets from Samples, by accident or intentional but this should not cause failures for others.

And perhaps a user might add a “Samples” folder containing all the audio samples personally recorded, meaning there may be other uses for that folder.

2 Likes

^ ^ ^ Yes, this is CRITICAL.

If you don’t ignore stuff properly, within a few days you will quickly exceed the file size of most free private git hosting solutions, and your repo will grow massive for no reason, bloated with discardable intermediate files that nobody needs that can become hundreds of megabytes in size.

1 Like

Thanks for your thoughts. There’s some really good, constructive stuff there!

  • I’ve tried to include all the little steps for those who are new or are missing some small detail that’s blocking their progress. Your 3 steps are more like 3 section headers each of which have several small steps involved.
  • I like your cloning method better than my –set-upstream method. I’ll switch the directions to using that.
  • I like using the command line as much as I can. That’s why these directions don’t use a GUI. I do like using a GUI for things like committing only a select few of the changed files or for viewing differences in files.
  • Yes, there are ways to set up your credentials so they work in the future without having to be set up again. That may be one thing that feels smoother for you than my directions above. My steps above try to help someone who hasn’t done this yet.
  • I wasn’t saying to not include a .gitignore long term. I was simply saying to add it yourself later. When using the set-upstream command to try to link an existing remote git repo and a local folder, I have had issues if the remote repo has any contents/commits. If it’s completely empty it works. But again, your cloning method seems a little better so I’ll switch to that.
  • The chicken and the egg is a great analogy. That’s certainly one of the obstacles that my directions are meant to solve.
  • You aren’t able to call git clone if you don’t have credentials set up. This is the other major obstacle these directions aim to solve. This is why I use the personal access token route. There is the credential-manager that will let you set up the token once and then not have to paste it into the clone url each time. Perhaps I’ll add directions for that if it seems best.
  • Good catch with the Packages folder. I forgot to say you must not ignore the manifest.json and packages-lock.json if you do ignore the Packages folder. There’s package that I import from the asset store that gets saved locally in the package folder. I don’t want them committed to the repo since I don’t edit them so I will ignore the Packages folder but not those 2 important files in it. But I’ve removed this direction since it’s optional and likely to confuse people.
  • Same with the Assets/Samples folder. I don’t like committing things that I don’t need to edit myself for my projects. But again, I’ve removed this from the directions to not confuse anyone.

Sure, but not really anything that couldn’t be done with some common sense. If I expand it:

  1. Create GitHub repo
  2. make these choice on that page
  3. copy the URL
  4. then git clone
  5. create Unity project in any folder other than the cloned one
  6. close Unity project
  7. move all contents to cloned repo

I once did too. I sometimes still do where it makes sense. But I’m generally on the fence when the command line is as complex as git. Or regex. And such. We have great UI tools for almost anything these days. I used to write scripts to mass rename files. These days I’d look for a mass file renamer, and including the download and install it’ll be a huge timesaver, especially if it has a preview feature. :wink:

If you’re very familiar with the command line it may help, but it also tends to forget all things you typed when that Terminal window is closed. Ugh.

That’s awesome but realize how much harder it is to do many common commit activities.

For one, I inspect and either accept or reject EVERY single proposed diff when preparing my commits, except when they truly reach a scale that makes this impossible, such as prefabs / scenes YAML, or binaries.

For two, I often break commits into (two or more) smaller commits when a common (shared library) and specific (application) use is involved.

These are just two simple every-single-commit things things. YES, yes they are 100% totally doable with the command line, but whoo boy, you gotta like a lot of pain to do it with something like vi or any generic text editor, staging one line at a time, or one set of lines at a time.

And if you screw it up or do your job less-optimally because you were using the command line, you don’t get a “get out of jail free” card. You still have to fix your repo.

Correct tool for the job, always. I use a mix of command line git and Sourcetree GUI.

And for diffs and merges, nothing beats Perforce’s p4merge. The coolest bit about it, and little known, is that it works for anyone anywhere all at once .. I mean with any app. You can even manually open two (or three) files and compare them.

1 Like