Your new BFF, Github Copilot

🤖 Github Copilot has been out for a while, but now it offers even more of an edge as it utilizes GPT-4 to generate output.

It’s wonderful for:

  • Writing code more quickly… and sometimes, writing quicker code (I’m not a world class optimization programmer, okay)
  • Letting AI tackle the syntax that you struggle to remember
  • Extending and refactoring
  • Explaining code
  • Understanding and fixing errors
  • Documenting code
  • Writing tests

There are other emerging free variants of this tech, but Copilot is the supreme option at the moment. An individual plan is available for $10/month or $100/year. You can learn more about plan differences and pricing here.

With support for a range of languages – Python, C#, JavaScript to name a few popular ones – it’s a fun, valuable tool to empower you on your tech journey.

The examples in this post will be C# in a Unity game dev environment, but the uses are limitless no matter what you’re trying to achieve through code. I’ll also be using Visual Studio Code IDE with the following Github Copilot extensions.

Extensions used in VSC

Giving the right context

You’ve probably played around enough with some of these LLMs to know that AI cannot read your mind. Working with Github Copilot becomes increasingly rewarding with how mindful you are about formulating your requests. Think about it as if you were working with a peer – they need the right context in order to actually make your job easier. Otherwise they will just waste your time.

Giving Github Copilot adequate context is going to yield better results. And fortunately, there are many ways you can go about this! Many of these should be no problem if you have smart programming practices already.

  • High-level comments
  • Opening existing project files
  • Libraries and references
  • Meaningful names
  • In-line comments

I’ll show a few quick examples of each below.

High level comments

You can write a short summary on top of your scripts to paint the top level picture to Copilot about what that file is responsible for.

High level comment on a script for a Unity project

Opening existing project files

Github Copilot will take context from other files you have open in your IDE. It doesn’t have full access to all files, but you can open them to give context.

⚠️ BIG WARNING ⚠️: Sometimes, this may work against you, especially when you want to break out of the coding style and patterns you have been using in your project. Try to close other files if you this is causing you annoyance.

A few relevant files open

Libraries and references

It doesn’t need to be comprehensive, but leading Github Copilot with clearly defined libraries and variables in your scripts helps further describe the sort of implementation you are after.

Meaningful names

Name things in smart, readable ways.

✅ Do this
🚫 NOT THIS!

In-line comments

This may be one of the more known ways to instruct Github Copilot. Use brief but specific comments where you want to add something in your scripts.

See below example. If you write a comment as a prompt in your script, it will predict what you are after.

Copilot is giving you output based on your inline comment

Many times, it will be exactly what you wanted – but it’s important to always verify by looking over the output and testing it out yourself.

If you are happy with this as a base, you can press TAB to complete it.

Ta-Da!

You could have also started writing the function yourself if you had preferences you wanted it to consider to make a more accurate prediction.

Anyway, I worked with Copilot to quickly make this script for spawning bugs around the map in a game. This is purely for demo purposes and not the perfect script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// a simple script to randomly spawn bugs around the world at random intervals

public class BugSpawner : MonoBehaviour
{
    [SerializeField] GameObject bugPrefab;
    [SerializeField] Transform[] possibleBugLocations;
    [SerializeField] Transform[] myArray;
    Transform selectedLocation;
    int randomSpawnSpotRoll;

    private void Start()
    {
        StartCoroutine(RespawnBugRoutine());
    }

    private void RandomSpotLogic()
    {
        int chance = Random.Range(0, possibleBugLocations.Length);
        if (chance != randomSpawnSpotRoll)
        {
            randomSpawnSpotRoll = chance;
            selectedLocation = possibleBugLocations[chance];
            Debug.Log("Bug Location " + selectedLocation);
        }
    }


    // create the instantiatebugonspot method
    private void InstantiateBugOnSpot()
    {
        if (selectedLocation.childCount == 0)
        {
            Instantiate(bugPrefab, selectedLocation);
            StartCoroutine(RespawnBugRoutine());
            Debug.Log("Instantiating bug in " + selectedLocation);
        }
        else
        {
            StartCoroutine(RespawnBugRoutine());
            Debug.Log("This location was taken: " + selectedLocation);
        }
    }

    // create the RespawnBugRoutine coroutine
    private IEnumerator RespawnBugRoutine()
    {
        // wait for a random amount of time between 10 and 300 seconds
        float timeTilNextBug = Random.Range(1f, 2f);
        Debug.Log("Coroutine started: Next bug in this many secs: " + timeTilNextBug);
        yield return new WaitForSeconds(timeTilNextBug);
        RandomSpotLogic();
        InstantiateBugOnSpot();
        Debug.Log("Bug spawned and coroutine ended.");
    }

}

To give it a test, I created a GameObject in my scene called BugSpawner and chucked the script on it. I then made some child GameIObjects to serve as potential spawn locations that I could drag into the array. Let’s see if it works.

Quick and dirty setup in Unity
Wow! You can see “Bugs” (actually fish 🐟 because I was lazy) spawning in short intervals once we go into Play Mode.

What else can we do?

Well, we can further refine the code ourselves, or work with Copilot to tweak it more if it wasn’t quite what we wanted. We can improve the codebase with documentation and refactoring, and even extend it to include more functionality.

Github Copilot Chat

Once you have the Copilot extensions in VSC, you should see a chat bubbles icon on the left panel of VSC.

This allows you to interact with Github Copilot in a more standalone chat area. It will answer coding-related questions and can help you with implementation outside of just providing specific code for your scripts.

Continuing to work in scripts

Let’s go back to our BugSpawning script. If we highlight the code, then right-click, we see we can access several options from Copilot.

We’ll go through each of these options.

Right-click highlighted code to access Copilot options

Start Inline Chat

You can ask it to help you make modifications to code by highlighting code, right-click -> in-line and asking a question.

🔥 HOT TIP: You can quickly open this inline chat by using CMD + I on Mac or Ctrl + I on Windows!

Asking an in-line chat question about highlighted code

If it has code change suggestions, it will show a side-by-side comparison of your code with any of its suggested additions in green and any removals in red.

You have freedom to accept, discard or regenerate the output. If you aren’t getting the result you want, revisit the wording of your question to ensure it is specific and simple.

It presents some changes and we can choose if we accept or discard them

/explain – Explain This

The /explain option is great for explaining code. (Remember, you can use CMD/Ctrl + I and /explain to access this more quickly than the menu nav.)

In the Chat panel, it will generate an explanation of the variables and methods in your script, as well as providing other question suggestions it thinks you may have at the bottom.

You can go back and forth with the AI to get increased clarity.

/fix – Fix This

This is a handy option but again, relies on you to provide adequate context.

I have found that when using /fix without context on a chunk of highlighted text that is syntactically correct, Copilot often does silly things like recommend library imports that it thinks you are missing despite them being present on the top of your script.

I removed a bracket to make an obvious issue with this code chunk, and you can see it immediately knows what is up when you go to fix. It gives a short explanation under the input box and some code edits.

Suggestion to add a closing bracket

It’s best to provide context about what needs to be fixed. See below. This is a dumb example but you get the picture.

It is suggesting we update the time range for spawns

/doc – Generate Docs

❤️ I LOVE THIS FEATURE.

Let’s say you are working with other folks and are expected to maintain a beautiful codebase. /doc helps you create documentation for your methods quickly!

Creates doc suggestion for this method

I accept it. Now when I hover over the method wherever it is called, we can get a snapshot of what it does.

Documentation popup when I hover over RandomSpotLogic() calls

Here is a different example where it shows a method with parameters.

The documentation will help understand not only what a function does, but also what parameters it takes.

/tests – Generate Tests

Lastly, you can generate unit tests for a selection – which is very powerful and replaces a boring but important task. 🦾

I won’t show any examples here, but give it a try yourself. It will likely suggest creation of a new file to handle the testing logic. You can always chat with Copilot to help you with implementing the tests.

Other helpful Copilot features

Here are a few little bonus I wanted to throw in so I don’t forget.

Drafting Commit messages

If you go to the Source Control tab in VSC, you can use Copilot’s help to have a stab at a commit message based on your file changes. If you are pedantic about your commit messages, you can always edit it to perfection after it provides you with a draft.

Simply click the ✨sparkly✨ icon where you’d write your message and see what it returns.

That sounds good! I will commit with that message.

Help in the terminal

Just as you can highlight and ask Copilot for explanations on code in your scripts, you can get similar support in the terminal. Simply highlight the text you need a hand with and right-click -> Copilot -> Explain This.

Simply ask to Explain This on any terminal code or output.

That’s all for now

No one reads blog post conclusions anyway so I’ll end here.

👋