Setting up git mergetools for Unity

If you have Git set up with Unity, you will more often than not find merge conflicts ruining your Unity scenes and prefabs, removing changes and sometimes losing data. Luckily Unity includes a utility to automatically merge these conflicts, and despite it being seldom mentioned in the documentation, works very well.

Prerequisites

  • Unity (The tool has been packaged since about 4.5, but try and use a newer version of Unity if at all possible)
  • Git CLI - available here. I’m not going through how to install it here.
  • A fallback mergetool. I recommend Perforce Merge. Just accept all defaults during installation.

Setup

In unity inside the editor settings (Edit > Project Settings > Editor), under Version Control you must set Mode to Visible Meta Files and under Asset Serialization you must set Mode to Force Text. This will ensure all binary files are serialised as Ascii files.

In Git Bash, type

notepad ~/.gitconfig

And append the following lines:

[merge]
	tool = unityyamlmerge

[mergetool "unityyamlmerge"]
	trustExitCode = false
	keepBackup = false
	cmd = 'C:\\Program Files\\Unity\\Editor\\Data\\Tools\\UnityYAMLMerge.exe' merge -p "$BASE" "$REMOTE" "$LOCAL" "$MERGED"

What this does she isn’t overly important, but know that the path in CMD must match your Unity path (It’ll be different on MacOS), but ensure the double slashes remain. The path is probably correct on most default setups.

This should be all the setup required provided p4merge was installed with default location.

Using Git Mergetool

Next time you run git merge and are faced with a conflict, all you need to do is run

git mergetool

And it will automatically resolve most conflicts. On the off chance that it can’t automatically merge it will open p4merge and highlight the conflicts. Inside p4merge all you need to go is select the version you want (left, right or hold shift and select both) for each conflict inside the file, hit save and close the window and it will resolve the conflicts. Back inside the terminal you just need to run

git merge --continue

And the merge will finish successfully.

Good luck and happy merging.