UNITY - Introduction to Github for Unity
Teams use versioning software to both keep track of changes and share work on project. Github, using the Github Desktop client, is a free and effective versioning tool, if used properly
Getting Started:
[A]: Github Repo Set-Up
      (one person per team!)

[B]: Local Clone Set-Up
      (everyone!)

[D]: Working with Branches
      (or not!)
[E]: Resolving GitHub Conflicts
and safely removing the repo
[C]:Update Process
Steps for how to pull and push your changes!
[F]: Learn More About GitHub, including linked Discord pushes and automatic Unity WebGL builds!

UNITY TUTORIAL: GITHUB FOR COLLABORATION (Source video )
TERMS:
    "Repo" = Repository; the online folder holding your team project, hosted by GitHub.com.
    "Clone/Local Repo" = The repository copy located on your computer, updated with Github Desktop Client app.
    "Fetch" = In GitHub Desktop, refresh the History list to see what changes have been made.
    "Pull" = Copy all recent changes to your local repository.
    "Summary/Commit" = Type a description of the changes you mde and hit Commit to prepare to upload..
    "Push" = Upload the changes you made to the online team repo, so others can see them with Fetch and Pull them to their own machines.
    "Conflict" = When a changed file on a local copy of the game cannot be Pushed because someone else has Pushed a different copy since the last time the first person Pulled (downloaded teammate changes). This is usually resolved by the first person documenting and deleting their work ("Discard" their changes in Github), Pulling the version already on GitHub, and reproducing their own work in the new copy of the file.
    "Revert / Undo" = Don't do this in our team projects this semester. Ever, ever, ever. Contact us for alternatives!

 
[A]: BASIC GITHUB REPOSITORY SET-UP (OnGitHub.com):
1. EVERYONE ON THE TEAM SIGN UP ON GITHUB.COM AND CHOOSES A USERNAME:
Go to Github.com to make an account login: email, password, username.
Share your username with your teammates and teacher. Jason's username is Darmatage.

2. ONE PERSON PER TEAM: CREATES THE REPO ON GITHUB.COM:
a.
On GitHub.com, hit the [Start a Project] button or [New] button (upper left).

b. Choose a repository name (no spaces), and add a GitIgnore and choose Unity (will need to be replaced) before hitting [Create Repository].

c. Before uploading your initial Unity project, replace the GitIgnore on your computer with this GITIGNORE, to be sure only core project assets get shared (and computer-specific settings are ignored).

d. Add your teammates to this repository: Choose the Settings tab and In left-Menu, click "Manage Access". Hit [Invite a Collaborator] to add your teammates' GitHub usernames to this repository (sends them an invitation email from your username).

 
[B]: LOCAL PROJECT SET-UP (on your computer):
1. Download the Github Client: Go to desktop.Github.com and download the Github Desktop client installer. Hit Run. When prompted, enter the same email and password as for the GitHub account you created (File > Options to reset the login if needed).

2. FIND the INVITE in your EMAIL, hit [View invitation] (only opens the right page if you are signed into GitHub) and then hit [Accept invitation]. Please do not try to access the repo with just the URL: you need the personalized invite!

3. Create a folder where you want your local copy of the team repository to be located (like your desktop). I like to name this folder "MyGithub".


4. In GitHub Desktop: Click the Middle Option: Clone Repository (or Current Repository > Add > Clone Repository)
The repository should be available on your list of GitHub project/s.

NOTE: If the repo is not visible in GitHub Desktop, you can go to GitHub.com, enter the repository, click the green [Code] button and click "Open with Github Desktop" (or copy the URL from the GitHub site by clicking [Clone or Download]).

Choose your Github folder location and hit [OK] to create the repo folder within (It will have the repo name as entered on theGitHub site). This folder is now linked through the Desktop client to Github!



4. ONE PERSON PER TEAM: CREATE THE INITIAL UNITY PROJECT:
a. Create the new, initial Unity Project as a Project folder inside of your GitHub Repository Folder.
b. Edit > Project Settings > Editor.
        Version Control: Set "Mode" to Visible Meta Files.
        Asset Serialization: Set "Mode" to Force Text.
c. Replace the default Unity GitIgnore located at the top of the local folder with this Better GitIgnore script (Removes the slashes at the start of pathnames to be sure no Library, etc files are uploaded).
d. Upload this work to the team repo through











Primary GitHub work to UPDATE the project every day:

 
[C]: PROJECT UPDATE PROCESS:
(1). Fetch / Pull    
(2). Make Changes    
(3). Summary / Commit / Push.

(1). ALWAYS START BY FETCH / PULLING:
Before doing any work on the project, hit [Fetch origin] in GithubDesktop to find changes uploaded by your teammates, and then hit [Pull origin] to copy those changes to the local repository folder on your computer.

(2) COMMUNICATE AND MAKE YOUR CHANGES:
Alert your team about which Unity Scene you will work on, then get to work. Different team members can work on different scenes at the same time, but not the same one. Only one person can work on a specific Scene file at time. If two people make changes to the same file, a merge conflict will be created when they try to push, and one of those people will need to discard their changes.

To create content for a scene that someone else is using, create content in an untitled or temporary scene and drag it into the Project panel Assets folder to turn it into a Prefab. Upload the prefab and it can be aded to the desired Scenes.



(3). HOW TO UPLOAD YOUR CHANGES:

IN UNITY: When you are done making changes:
hit File > Save (to save the current Unity Scene) AND
File > Save Project
(to save project-level changes, like animation work or build settings).

IN GITHUB DESKTOP: You will then see your Changes listed in the GitHub Desktop client to be shared with your teammates.

    a) Type a short Summary of changes (Always include a Summary, and be sure it describes the key updates / additions).

    b) Hit the blue [Commit to Master] button (lower left) to commit your changes to your local copy of GitHub, to be ready to publish.

    c) Hit the blue [Push origin] button to publish your changes to the GitHub repository. Your changes are now available to your teammates, who need to “pull” those changes to make them part of their own local copy of the project.






REMEMBER: GitHub and Unity cannot merge two copies of the same Scene file (game level), so only one person should ever be working on a particular Scene at a time. If two people want to work on the same Scene, they need to do so sequentially:



(Step 1): Team Member A Pulls the recent changes to the project in GitHub.
Member A then works on the Scene in Unity and saves their changes: File > Save Project.
They Summarize, Commit and Push their changes in GitHub.
Finally, they alert the team that the Scene is released for someone else to change.



(Step 2): Team Member B Pulls the recent changes to the project.
They then work on the Scene in Unity and save their changes: File > Save Project.
They Summarize, Commit and Push their changes in GitHub.
Finally, they alert the team that the Scene is released for someone else to change, etc.

Even though only one person can make changes to the actual Scene at a time, everyone else can still make other changes to the project at the same time, including creating Prefabs for the player or AI characters, environment objects, scripts and visual or sound effects. These can be built in temporary new scene files and dragged into the Project panel to make a Prefab that can then by Pushed to GitHub for all to see and use. Only individual Scene files must be carefully “owned” by one person at a time.



 
[D]: WORKING WITH BRANCHES:
GitHub Branches serve an important purpose in traditional software projects. Branches allow individual programmers to work on a copy of the project, isolating their changes to test that their work functions before sharing it with the team.

For this Game Design course, you are encouraged to NOT use GitHub Branches. Unlike a traditional software project, most things in Unity are Scenes, art assets, or Prefabs, which do not merge like Scripts. Branches in Unity can easily lead to GitHub conflicts, where two people tried to make objects with the same name.

You are encouraged instead to all work on the default Main branch, in separate Scenes named for your name, and to communicate every day about what you are working on to make sure you do not create duplicate assets. Most important of all: Test your work to be sure there are no compile erros, and PUSH YOUR WORK EVERY DAY. If you spend a week not pushing, you can expect conflicts.


All that said, if you are deeply concerned that the changes you will make could negatively affect the Main project, but still want to test them out with your team, you can make a branch off of Main.

GitHub Branches contain a separate copy of the project (as it existed when the branching occurred). When we "Switch" between branches in GitHub desktop, our actual Unity project only shows the files for the active branch!
TO CREATE A NEW BRANCH FOR YOUR WORK:
1. Click the middle "Current Branch" tab.
2. Towards the top of the rolldown, choose [New Branch].
3. In the box that opens, name the Branch (I suggest naming it your name, written as YourName, in humpCap notation).
4. Hit [Create Branch].

WORK IN YOUR BRANCH:
When you choose a branch to make it active in GitHub, it is also active on your computer and in Unity. Github swaps out which files are currently available on you machine based on your active branch. You can switch to any branch to see the version of the project there!

Try to be careful to only change your intended files in your separate branch. Idf you change them in both your separate branch and in the Maoin branch, you will get a conflict when you try to merge them that will result in changes beign discarded from one of them.

TO MERGE YOUR BRANCH WORK BACK INTO MAIN:
We can easily copy ("Merge") the work in your branch back into Main.
1. Switch to the Main Branch (click the middle "Current Branch" tab and click on Main to make it the Current Branch).
2. Open the middle tab again, and at the bottom of the rolldown click [Choose a Branch to Merge into Main].
3. In the box that open, select your branch (the one you want to Merge) and hit [Merge origin/YourName into Main].
NOTE: The original, separate Branch is preserved in this process, so it can continue to be used for changes or as a backup copy of your work!

DO NOT REVERT, do not hit [UNDO]
Get stuck on something? Ask for help. Reverting in a separate branch can cause all sorts of problems, just like reverting in Main. The [Undo] button is worse. We have many other tools to fix conflicts or other problems. Contact us for help.



 
[E]: RESOLVING A GITHUB "CONFLICT":
Accidents happen. Someone may not remember to save their changes or Push those changes on GitHub, and then someone else may dutifully Pull, not get any changes (because they were not uploaded), and then work on that scene, not realizing they are creating a Conflict: a situation where there are two copies of the same file on GitHub and one needs to be discarded from the Repository.

Communication is key: use an active Discord channel or other tools to alert your team when you want to make changes to a Scene, and again when you are releasing it for others to work on. Be good about saving your project and Pushing your changes, at least every day you work, ideally more often.

If there is a conflict in GitHub: The person who did less/more disposable work must document their work (write down a description of changes in order to reproduce them), delete the file from their local repository, and Pull their teammate’s version to their machine, effectively moving forward with their teammate’s version. They can then repeat their changes on that version of the file.

MOST IMPORTANT THING ABOUT CONFLICTS: Ask us for help if they arise!


2. DO NOT REVERT. ALSO: DO NOT HIT THE "UNDO" BUTTON BELOW COMMIT.
Revert (or the Undo button) causes major loss of data, expecially if you merge the Main repo into your branch, and then revert or "undo"-- you are undoing not just the merge, but all of yoiur teammates' work since the last time you merged! ACK!
DON'T REVERT
DON'T HIT "UNDO".

ESPECIALLY, DO NOT REVERT OR UNDO IN A BRANCH.

WHAT SHOULD I DO INSTEAD?
As a last resort, it is better to fix big problems by replacing your local repository:
1. Remove your local copy of the repository from GitHub.
2. Remove this project from Unity Hub.
3. Rename this project [OldName]_old. It still exists, but neither GitHubDesktop nor Unity Hub can see it.
4. Make a new folder for the team repo.
5. In GitHub, clone the project into this new folder.
6. In Unity Hub, [Add] this new copy of the team project.
You now have a clean start!
BUT, if your team agrees it is time to revert (ugh), here are the steps:

TO REVERT: To rollback a commit that was already pushed to the shared repository, go to the History tab in the GitHub Desktop. RightClick on the commit you want to rollback (left column; this is why Summary names are so important) and select Revert this commit. Then Push Origin to upload your changes to the shared repo.

NOTE: When you revert multiple commits, it's best to revert in order from newest to oldest. If you revert commits in a different order, you may see merge conflicts. See https://help.github.com/en/desktop/contributing-to-projects/reverting-a-commit




PROBLEM A: If you try to Push changes without Fetching/Pulling more recent changes first, you’ll get an alert: 'Newer commits on remote'.

Hit [Fetch] to refresh the change history, then [Pull origin] to get the latest changes before Push origin to upload your changes.



PROBLEM B: If there are conflicts because you both changed the same lines of code or assets, then you’ll get this pop up (see image):

You’ll have to "resolve" the conflicts before you can Merge. Click on each conflict to resolve each one (see below), then [Commit merge].

To resolve the conflict, you must decide which change to keep.
In this case, 2 team members both changed the layer order for the background assets. One put the sprite at 35 and the other put it at 45. Decide which one to keep and accept that one by clicking on either 'Accept Current Change' (the edit your TEAMMATE already pushed to the repo) or 'Accept Incoming Change' (the edit YOU made and are tried to upload after).  In some rare cases you may want to 'Accept Both Changes'.



When all conflicts are resolved, you can hit [Commit merge].



Then hit [Push origin] to upload your changes to the team online GitHub repository.
PROBLEM C: Discard vs Ignore
Have changes showed up in your Change list that you KNOW should not be pushed? You can Discard those changes by selecting them and right-clicking on them and choosing the top option, Discard. The changes will be undone on your computer.

Please do not choose the Ignore options-- they add ignore restrictions to your project GitIgnore file.





PROBLEM D: Everything On My Computer Is On Fire
Does your local copy seem to be in terrible shape, but the team's main repo on Github.com is still fine? It may be time to re-clone the repository to a new location on your computer and move forward from there.

As noted above, here are the 5 steps to re-Clone the repo:
1. Open GitHubDesk Desktop, RightClick your old team repo and REMOVE it.

2. Unity Hub: find the old team game in the list and REMOVE it (click the 3 dots on the right-side).

3. On your computer GitHub folder (or wherever you put your old game), create a new folder called "YourGameName_v02".

4. In GitHub Desktop clone the repo into this new folder. The project may be nested one folder deeper than your previous clone -- that is fine.

5. In Unity Hub, add the new project: click [Add] and navigate to inside the project folder (you should see Assets, etc but not click on it).

Note that the repo does not include folders like "library", due to the correct gitignore.
Those folders will be created on your machine when you run the new game in Unity for the first time, but will never get pushed to the repo.


Are you using the Command Line to acces Git?
Learn more about solutions to problems with Git here.

Changing your Git ID, or fixing the "Author Unknown" Error:

If you get the "Author Unknown" error, or want to change your Git ID for commits, go to:

    File menu > Options (PC) or
    Github Desktop menu > Preferences (Mac)

and choose the Git tab on the left to set your username and email to the same ones as your GitHub.com account.


 
REMOVING the Repo from your Computer:
As a last resort, bad local conflicts on your computer can sometimes be best managed by removing the repo from your machine and re-importing a clean copy.
We call this method "burning it all down with fire".

Also, when the project is over, you can use this system to remove the Repo and free 1-2 gigs of space on your computer.

1. First, make sure Unity and Photoshop are turned off, as well as your IDE (VSCode Notepad++, etc), anything that speaks to the files in your projects.
2. In GitHub, click on the upper-left "Current Repository" button to see your projects.
3. RightClick each to choose the bottom "Remove" options.
4. Select "Also move this repository to the Recycle Bin", and hit the [Remove] button.

NOTE: If you get a failure in this process (usually if a program is still speaking to files in the repo folder), you can use GitHub to Remove WITHOUT moving the files to the recycle bin, and when GitHub is done, move the folder to the recycle bin manually.

Naturally, do NOT delete the project files manually first, and then push those changes to the repo, or it will erase the project for everyone.



 
[F]:TAKE YOUR GIT WORK FURTHER:

Github Desktop
is a decent tool for beginners, but it lacks finesse. For a lot more control over the flow of branches in your project, consider downloading and using UnGit.

To improve your understanding of Git and Branching, explore these visual tutorials:
https://LearnGitBranching.js.org/



Want to motivate your team to greater heights of GitHub glory?
Integrate GitHub into your team DISCORD channel with Discord Webhooks,
so that each new post can be announced there.


Use GitHub to host a WebGL build and automatically update with every Commit:
These set-up notes come from Amogh Subhedar:

1. In GitHUb Desktop, make a new branch, and name it "builds".
(ideally, this branches off the very first commit, to have less to delete in step 2)

2. Delete all Unity project content and folders in that new branch (NEVER merge back :) ).

3. a) Make an initial WebGL build from your Unity project (html file, build folder, template folder).
    b) Add ONLY the index.HTML file to the builds
branch (at top, next to the GitIgnore file).
    c) Publish (push) this new "builds" branch.

4. a) Go to GitHub.com to open your project.
    b) Open the Settings tab, and on the left column click to open "Pages".
    c) Click "None" to choose the "builds" branch for the webpage.
    d) Hit [Save] (Game code continues in Main, but now webpage gets the default root of "builds").

5. Create a "workflow" file in main branch:
    a) On the GitHub.com site Main branch, open the Actions tab.
    b) Hit "New Workflow" (upper left) and then "Set up a workflow by yourself" (near top).
    c) Name it mainBuildMaker.yml.

6. a) Replace the content of mainBuildMaker.yml with this script.
    b) Customize the script: Near the top of this script under env, change 2 items:
        UNITY_VERSION : set the correct Unity version,
        PROJECT_PATH : set to your Unity project name (the folder that holds the assets, etc ).
                (NOTE: for UNITY_LICENSE : leave the year as 2019)
        Be sure that the version of Unity Builder is correct (change the final version # if needed):
                line 32: uses: game-ci/unity-builder@v2.0-alpha-14
    c) Hit [Start Committ]. In window that opens, hit [Commit Changes] (yes, this goes to main).

    To edit this .yml file again later:
        Go to the Main Branch > Code tab, open .gitHub/Workflows, and hit the pencil / edit button.

    NOTE: This script calls two 3rd party GitHub plugins: Unity Builder and Git Auto Commit
    (No need to install anything-- they exist in GitHub's ecosystem).
    Unity Builder creates a new Build folder and TemplateData folder.
    Git Auto Commit makes this happen after each commit.

7. Add a license file for the builds: Use this process to generate the license file with your Unity license (see here for how to find and download the GitHub Artifact file):
    a) Create a new custom workflow called activation.yml (as in step 5 above).
    b) Replace the content of activation.yml with this script.
    c) Manually Run this file:
        Click Actions tab (top).
        Click "Acquire Activation file" (left).
        Click [Run Workflow] (right)
    d) When run is done, RightClick new "Acquire Activation file" link (bottom) to "Save Link As".
    e) Save the .ZIP file to your desktop and extract the Unity_v20xx.x.xxxx.alf file.
    f) Go to license.unity3d.com/manual:
        Upload the Unity_v20xx.x.xxxx.alf file.
        Choose (1) Personal edition, (2) Less than $100k, and then click [Download license file]
        Find the license in downloads (Unity_v20XX.x.ulf). It's OK to not match your Unity version.
    g) Add the license as a GitHub "Secret" (encrypted environment variable):
        Back in Github.com, open your repo > Settings > Secrets > Actions.
        Click [New Repository Secret] to create a new one.
        Set the Name to the same as in the yml file: UNITY_LICENSE_2019
        Under Value paste in the content of your license .ULF file (can be opened in notepad).
        Click [Add Secret].


IMPORTANT FIX NOTES:
[A] Make sure the project .GitIgnore file has [Bb]uild and [Bb]uilds commented # out, in both the build (!) AND main (?) branch, or the build will not push!

[B] Unity Build Settings: Choose WebGL, click [Switch Platform].
IMPORTANT: Hit [Player Settings] and under "Publishing Settings" set Compression Format from the default Brotli or Gzip to "Disabled". This should fix any WebGL issues in GitHub pages, but here are more fixes. NOTE: if the build keeps saying the compression is an issue after removing all compression, try emptying the WebBuilds folder once to make way for clean replacements.

[C] After step 7 has fully processed your first build, you will need to edit your index.HTML file (the one you initially comitted) to direct each url to the folder containing your build and the build file names (likely "WebBuild"):

Around lines 7-8:
                            <link rel="shortcut icon" href="WebBuild/TemplateData/favicon.ico">
                            <link rel="stylesheet" href="WebBuild/TemplateData/style.css">
Around lines 71-76:
                            var buildUrl = "WebBuild/Build";
                            var loaderUrl = buildUrl + "/WebBuild.loader.js";
                            var config = {
                            dataUrl: buildUrl + "/WebBuild.data",
                            frameworkUrl: buildUrl + "/WebBuild.framework.js",
                            codeUrl: buildUrl + "/WebBuild.wasm",

MAINTENANCE:
The library image that is cached after the first build will stay the "starting point" for future builds, meaning each new day of changes needs to be re-calculated for each new build.
Every few days of production update this library image to support faster builds:
In the mainBuildMaker.yml file, change the word after key in this line (CachedLibraryWeek2, etc):
                            29: key: CachedLibrary





Tutorials prepared by Jason Wiser, Madwomb.com, with Marianne Chiarella