Tag Archives: Unity

How To Setup A Github Repo For A Unity Project

If you’re not familiar with using Git you can take a peek at my quick guide Git It? or spend some time browsing the web to get familiar. If you are familiar with Git, you will need to install Git Bash for this tutorial. You can grab a copy of all the necessary install files right here: https://git-scm.com/downloads



Advertisements

The first thing we want to do is setup our new repository on Github. You will need to first create a Github account. Once you’ve created your account, you can click the little plus sign, in the top-right corner of your screen and select ‘New repository.’

This will take you to the ‘Create a new repository‘ screen to setup your new repo. You will need to provide a name for your repository and then select if you want it to be viewable by the general public. In this example, I will keep the repo private.

Advertisements

I do not want to create a ReadMe or .gitignore at this time but I will do so after I have created my Unity project. Go ahead and press that little green button, ‘Create respository.’

Now that the new repo is setup, Github will kindly provide you with some instructions on how to push your new project to this online repo.

Advertisements

But the first thing we need is to setup a new Unity project. I will walk through how to create a new Unity 2D project and then we will setup a .gitignore file to exclude any files we don’t want to include in our repo. Finally we will push all of our changes up to Github.

Let’s walk through the process.

You’ll want to open Unity Hub and create a new project.

Now that the project has been created you’ll want to navigate to the directory where the project has been saved. Once you are in the directory, you can right-click and select, ‘Git Bash Here.’ This will open the git command line.

Advertisements

The first command we want to run is ‘git init‘ this will initialize the git repo locally and allow you to start adding and commiting your unity project for source tracking.

Now that the repo is setup, we can run ‘git status‘ to view the files that we can potentially add to our repo, BUT before we add anything, we want to include our .gitignore file. This will allow us to only include the files we need, and allow us to ignore any temp or unneeded files.

To do this you will need to create a new empty text file and rename it to ‘.gitignore’ so that git will recognize this file as being the one that will tell us which files to ignore.

Now go ahead and open up the file in a text editor and in the contents of the text file we are going to include the files we wish to ignore. You can find a good example of what to include by searching on Google for a Unity .gitignore file or you can use the one here: https://raw.githubusercontent.com/github/gitignore/master/Unity.gitignore.

Advertisements

Once you’ve added that to the contents of the .gitignore file, you can save the file. Back in the git command line window you can run the ‘git status‘ command and see the remaining files we will include in our repo.

We will now run the ‘git add .‘ command which will include all of the files that are not ignored, to be a part of our project.

Advertisements

Next we will run the ‘git commit‘ command which will commit our newly added files to our main branch. We will actually use the ‘git commit -m‘ command so we can include a little message on what these changes are.

After adding our files it’s time to finally push them up to Github. To do this we will run two more commands. The first is the link this local git repo to the one on Github.com. The second is to push the changes from our machine, up to Github.

Github provides the first and second command for you:

Advertisements

Execute the ‘git remote add…’ command followed by the ‘git push‘ command (you may need to change the push command from ‘main’ to ‘master’) and you’re done.

You now have a brand new Unity project on Github. If you’re interested in knowing more on how to work with Git or Github leave a comment!


How To Create a Glow Effect In Your Unity 2D Project

This process took me entirely too long to actually figure out how to do myself. I even spent a couple of bucks on an solution off the Unity Asset store and still struggled.



Advertisements

I wanted to write this tutorial for anyone else that might want to add glow effects to their projects and to hopefully avoid them having to ride the struggle bus like I did. Take a peek at the end result here:

Play the game right here!

To get started, create a new Unity 2D project. Once created, open the Package Manager under the Window menu item and search for the Universal RP package, install it.

In the Project view, right-click and select “Create >> Rendering >> Universal Render Pipeline >> Pipeline Asset (Forward Renderer)”

This will create 2 objects, name the first object 2D Render Pipeline and delete the object named 2D Render Pipeline_Renderer.

Advertisements

Right-click in the Project view again and select “Create >> Rendering >> Universal Render Pipeline >> Pipeline Asset (Forward Renderer)”

Rename this object to 2D Renderer. You should now have two render objects like this:

Click on the 2D Render Pipeline object and in the Inspector, drag the 2D Renderer object into the Renderer List. Also check the HDR checkbox under Quality.

Advertisements

Now under the Project Settings which can be found under “File >> Build Settings >> Player Settings” select the Graphics tab and set the Scriptable Render Pipeline Settings to the new 2D Render Pipeline object we just created.

Under the Main Camera Inspector you will see some new options, check the box for Post Processing under the Rendering drop down.

If you want, you can change the background of the camera to black to help add to the glow effect.

Advertisements

In the Hierarchy, right-click and create a new 2D Sprite. On the Sprite Renderer of the new object, select the Knob sprite (or provide your own).

Also on the Sprite Renderer, set the Material option to Sprite-Lit-Default (you will have to click on the little eye, to show all of the options).

Advertisements

Now all you have to do is add a Light object to your new sprite and viola, he shall GLOW!

You can play around with the effect of the glow by tweaking these settings on the Point Light 2D

Advertisements

If you want to watch the live stream of the making of this tutorial you can check it out here: Twitch Live Stream or you can catch the shortened version on YouTube!


How To Build A Spawner In Unity

Spawning objects in Unity exists in just about every project out there. Whether we’re spawning enemies for a player to fight or collectables for them to pickup, at some point and time you’re going to need systems that can create and manage these objects. Let’s walk through what this can look like in a Unity 2D project.

There’s no best way to implement a system that creates objects and every project has slightly different needs but there are some commonalities and ways you can create your system to be reusable. For this particular example we’re going to look at spawning for Survive!

Advertisements

There are two main objects that are currently created in Survive using the current spawning system with a handful more on the way. The great part is that implementing each objects spawning logic and system is fairly simple after the first one is in place. Let’s take a look at how that’s done.

Currently we are creating two objects at game start. The white blocks that act as walls and the green enemies the player must avoid. Both of these are built using the same spawning system and code base. We do this so that we can then re-use these objects and scripts to easily add new features to our project. Here is what our spawner code currently looks like:

Advertisements
using UnityEngine;

public class Spawner : MonoBehaviour
{
    public GameObject objectToSpawn;
    public GameObject parent;
    public int numberToSpawn;
    public int limit = 20;
    public float rate;

    float spawnTimer;

    // Start is called before the first frame update
    void Start()
    {
        spawnTimer = rate;
    }

    // Update is called once per frame
    void Update()
    {
        if (parent.transform.childCount < limit)
        {
            spawnTimer -= Time.deltaTime;
            if (spawnTimer <= 0f)
            {
                for (int i = 0; i < numberToSpawn; i++)
                {
                    Instantiate(objectToSpawn, new Vector3(this.transform.position.x + GetModifier(), this.transform.position.y + GetModifier())
                        , Quaternion.identity, parent.transform);
                }
                spawnTimer = rate;
            }
        }
    }

    float GetModifier()
    {
        float modifier = Random.Range(0f, 1f);
        if (Random.Range(0, 2) > 0)
            return -modifier;
        else
            return modifier;
    }
}

And here is what our script looks like from the Editor:

As you can you see, our script allows us to pass in the ‘Object To Spawn’ which is the prefab of the object we want to create. We can then assign it an empty parent object (to help keep track of our objects) and from there we are free to tweak the number of objects it spawns at a time as well as if there should be a limit and how frequently they should be spawned.

Advertisements

With this approach we have a ton of flexibility in how we can control and manipulate object creation. We could attach another script to this object that randomly moves the spawner to different places on the screen (this is how it currently works) or we could create multiple spawners and place them in key locations on the map if we wanted more control over the spawn locations. The point is, we have options.

The best part about this approach is that we can easily include or add another object to use this same functionality with little effort. Here’s the same script, same code, but for creating wall objects:

And a third time for a new feature I’m currently working on:

Advertisements

Each object and system has it’s own concept and design to how it should work, for example the wall objects need to create so many objects quickly (higher rate) and then stop (reach their limit). The zombie objects need to be created over and over as the player destroys them but not as fast (slower rate). The new Heart Collectible needs to be created only once until the player collects it (limit).

When building objects and writing scripts in Unity we should always be thinking of how we can create something that is reusable. It might not be reusable in this particular project, but it can save you mountains of time when you go to the next project and you already have a sub-system like spawning built and ready to go!

If you want to take an even deeper dive, take a look at an article on Object Pooling: Taking Your Objects for a Swim that can help with performance issues you may run into while working with Spawning Systems.

Don’t forget to go checkout Survive and sign up for more Unity tips and updates:

How to Host Your Unity Game in AWS

One of the most difficult things to accomplish when creating new projects is making the project accessible. Typically, if you are creating a mobile application or even a web application, there is significant work to get that application deployed.

In this tutorial we’ll walk through how to get a basic Unity 2D project deployed to the web so that you can start collecting feedback.



Before we start, let’s set the bar. In no way do I claim to be a Unity or AWS expert. There are most likely pieces of this tutorial that are not complete. If you find an error or notice somewhere that something is incorrect, please let me know so that I can update it for everyone else!

Now let’s get nerdy!

So, first things first. If you haven’t already, create a Unity 2D project in Unity. If you’re not familiar with Unity, take some time to get up-to-speed at https://unity.com/. Once you feel a little more comfortable and are able to create a simple 2D project, head back over here.

Advertisements

Within Unity, head up to the Menu bar and let’s create a build. Select ‘File > Build Settings’ and under ‘Platform’ select ‘WebGL‘. If the option isn’t available you may need to open up Unity Hub and download the required assets for WebGL.

Before you build your project as WebGL, be sure to check ‘Development Build’ and that you have your Scene selected to be included in the build. Then go ahead and click the ‘Build’ button and select where you want the application to be built.

I don’t know that we need the ‘Development Build’ option checked every time but when I first attempted this process I found I wasn’t able to get the application working. After some research, I found there was a bug and/or workflow issue in Unity and creating at least one development build was required.

Now that your build is completed, the Unity side of things is done. You can test your build just to be sure everything is working by clicking on the ‘Build and Run’ button in the build settings window. I’d recommend making sure everything is kosher before going on.

Advertisements

Now let’s head over to AWS. If you don’t already have an AWS account setup, go ahead and take the time to do that at: https://aws.amazon.com/console/. Once you are setup, go ahead and log in to the AWS Console.

What we’re going to do is deploy our Unity project to an S3 Bucket (which is just an online folder) and host it as a static website.

Within the AWS Console, either search under Services for ‘S3‘ or find it in the list.

Once you’re in S3 you’ll want to select the orange, ‘Create Bucket‘ button on the far-right. Go ahead and give your bucket a name and then scroll down to ‘Bucket settings for Block Public Access’. Uncheck each of these options and then scroll to the bottom of the screen and select ‘Create Bucket’

Advertisements

You should be returned to the main screen and now see your bucket. Go ahead and select it. You should see a new button on the far-right to ‘Upload‘ with. Go ahead and select that button and upload your Unity project. When you upload, select ‘Add Files’ to add the ‘Index.html’ file and then select ‘Add Folder’ for each of the ‘Build’ and ‘Template Data’ folders. Once all items are added go ahead and upload them.

Back within our bucket, select ‘Properties‘ and scroll to the bottom of the screen under, ‘Static website hosting

Select the ‘Edit‘ button off to the right and match your settings like this:

Advertisements

Save those changes and head back to your bucket. Now select ‘Permissions‘ just next to the ‘Properties’ tab. Under permissions find the ‘Bucket Policy’ and select ‘Edit’. Paste in the following policy and replace the ‘Resource‘ with the name of your bucket. There are two spots to do this and I’ve named them, “YourBucketName’ below:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::YourBucketName/*"
        },
        {
            "Sid": "2",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1L55VHCJEWRMZ"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::YourBucketName/*"
        }
    ]
}

Now we are incredibly close to being done. Back in AWS, under Services, let’s now search for ‘CloudFront‘ and select it. On the CloudFront menu we’ll select ‘Create Distribution’ and then we’ll select the ‘Get Started’ button under the ‘Web’ option.

There’s not too much we need to change here. The very first setting ‘Origin Domain Name‘ you can click on and a drop down will appear for you to select your bucket. No other option needs changed and you can scroll on down to the bottom and select ‘Create Distribution’ to complete the setup.

Advertisements

Once the distribution is created, go ahead and select it to open it up and we’re going to make one final change before wrapping things up.

Under the ‘Error Pages‘ tab go ahead and select to ‘Create Custom Error Response’. On the new screen, select ‘Http Error Code’ as ‘403’ and under the ‘Customize Error Response’ option select ‘Yes’. When the new options appear, set ‘Response Page Path’ to ‘/Index.html’ and the ‘Http Response Code’ to ‘200: OK’ and save your changes. It should look like this:

Now, head back over to your S3 bucket and open it up. Inside your bucket select the ‘Index.html‘ file and on the ‘Object Overview‘ panel click on the ‘Object URL‘ link.

This should fire up your new static website, which will then kickoff the Unity application! Check out my example: https://lks-survive.s3.amazonaws.com/index.html

Advertisements

I hope this tutorial was able to help you get something roughly uploaded and hosted online. Remember that with AWS S3 there are some costs incurred to host your application online. My total costs are under $10 a month. If you have any feedback or suggestions to improve this tutorial please let me know!

For more Unity and AWS tips keep up with me by subscribing:

Happy Thanksgiving

Enjoy some turkey and have a little fun, click the link to play!

https://turkeygobbler.s3.amazonaws.com/index.html

Advertisements

How to Debug a Unity APK on an Android device with Visual Studio

Oh my goodness this was far too difficult… so I had to write it up! This guide assumes you have some experience with Unity, debugging in Visual Studio, and building APK’s (let me know if you don’t in the comments!).

If you’re using Unity, you’re coding in C#, and you’re using Visual Studio… Here’s how you can setup a remote debugger to debug your APK on an Android device.

I’m currently using the following tools but the steps are generally the same:

Unity v2020.1.7f1

Visual Studio Community 2019

Android Studio v3.5 & SDK

Samsung Galaxy S9

Step 1: When you build your APK you’ll want to tick 2 boxes on the build settings menu. ‘Development Build‘ & ‘Script Debugging

Step 2: Create your build as usual and copy the build to your Android device. Connect your Android Device to your PC via USB. Be sure your machine and Android device are connected to the same wifi network.

Step 3: If you haven’t previously, Enable USB Debugging on your Android Device.

  1. Open Settings
  2. Select System
  3. Scroll to the bottom and select About Phone
  4. Scroll to the bottom and tap ‘Build Number’ 7 times
  5. Return to the previous screen and find ‘Developer Options’ near the bottom
  6. Scroll down and select to enable ‘USB Debugging’
Advertisements

Step 4: Back on your computer, open up a cmd prompt (or terminal) as an administrator and change your directory to:

C:\Users\[user]\AppData\Local\Android\sdk\platform-tools

Step 5: Back on your Android Device, find the Android Device’s IP by going to:

  1. Go to Settings
  2. Go to ‘About Phone’
  3. Got to ‘Status’
  4. Find ‘IP Address’
  5. Write it down…

Step 6: Back in your command prompt enter the following command:

adb tcpip 5555

If you need some extra help see the Unity Documentation here

Step 7: Connect to your Device with this command using your IP from Step 5:

adb connect [YourIpAddress]:5555
Advertisements

Step 8: Open Visual Studio from within Unity and go to the ‘Debug’ menu option. Select ‘Attach Unity Debugger’

Step 9: You should see a small menu popup and it should display both your computer and your connected Android device. Select your Android device, set some break points in your code, and have fun!

Hopefully this guide saves you some time and headache on trying to figure this out. If you need more information on connecting your device that this guide doesn’t provide let me know so I can update it!