Gigi Labs

Please follow Gigi Labs for the latest articles.

Friday, May 31, 2013

Unity3D: Space Invaders (Part 4 - Collisions)

Hello again! :)

In the previous article - "Unity3D: Space Invaders (Part 3 - Prefabs)" - we implemented bullet-shooting in our Space Invaders clone. We developed a bullet prefab that we could then create during gameplay when the player shoots at an alien. However, bullets aren't much use if they don't hit something.

In this article, we'll deal with that problem, and allow bullets to destroy aliens upon impact.

First, we need to set up the scene so that the player can actually target an alien when firing. Creating a 2D game in Unity - which uses 3D coordinates - may sometimes be a little bit confusing. To help us get our bearings, let's put create background. From the GameObject menu, select Create Other -> Cube. Rename it to "Background". Resize and move it so that it is very thin, but covers the entire camera view:

Note: we could have used a Plane object here instead of a Cube, but when your game starts to get a little complex, you'll find that a Plane has a number of limitations that a Cube doesn't.

The Alien needs to be directly above the Player, if bullets are to hit it. In the Inspector, set the position of the Player and the Alien so that they have the exact same z-coordinate. Move things around and resize them so that they fit nicely into the camera's view. Give the Background, Player and Alien different coloured materials so that they can be clearly seen from the camera.

Since this looks a bit dull, go to the GameObject menu and select Create Other -> Point Light. Mess with the light's position and intensity (the intensity is in the Inspector when you select the light) until you are happy. In the image below, I also changed the alien's material, since the previous one didn't have very good contrast with the background:

Now, in the Assets panel, double-click the Alien script to open it in MonoDevelop. This is what we had from the article on linear interpolation:

public class Alien : MonoBehaviour
    private float startTime;
    // Use this for initialization
    void Start ()
        this.startTime = Time.time;
    // Update is called once per frame
    void Update ()
        float t = (Time.time - startTime) * 0.4f;
        float x = Mathf.Lerp(-5.0f, 5.0f, t);
        this.transform.position = new Vector3(x, 5, 5);

First of all, if you changed position of the Alien, you may need to adjust the code in the Update() method. You can find out the minimum and maximum x coordinates by placing an object at the left and right edges of the Background and taking note of its x-coordinate. A bit of trial and error may also help. For me, this works:

    void Update ()
        float t = (Time.time - startTime) * 0.4f;
        float x = Mathf.Lerp(-2.5f, 2.5f, t);
        this.transform.position = new Vector3(x, this.transform.position.y, this.transform.position.z);

If you didn't do the exercise at the end of the linear interpolation article to make the Alien behave in a proper Space Invaders manner, let's at least make it move back and forth so that the player can hit it at some point. Add this variable to the Alien class:

    private bool movingRight = true;

The Update() method thus becomes:

    void Update ()
        float t = (Time.time - startTime) * 0.4f;
        float x = 0.0f;
        if (movingRight)
            x = Mathf.Lerp(-2.5f, 2.5f, t);
            x = Mathf.Lerp(2.5f, -2.5f, t);
        if (x >= 2.5f)
            movingRight = false;
            this.startTime = Time.time;
        else if (x <= -2.5f)
            movingRight = true;
            this.startTime = Time.time;
        this.transform.position = new Vector3(x, this.transform.position.y, this.transform.position.z);

All this means is that the Alien starts moving right. When it hits the right edge, it starts moving left instead. It keeps moving back and forth between the left and right edges. Try it out in Unity and adjust coordinates if it doesn't feel right:

We are now ready to deal with bullets hitting aliens. Select the Alien, and from the Component menu, select Physics -> Rigidbody, and be sure to turn off "Use Gravity":

This is necessary for the collision to work, as are the box collider on the Alien and the capsule collider on the Bullet. Colliders are just things that help check when an object hits another, and when you create a standard object (such as a cube), colliders are normally added by default.

So now, go double-click the Bullet script to open it in MonoDevelop. Add the following method:

    void OnCollisionEnter(Collision collision)

The OnCollisionEnter() method is called when one collider hits another. The collision parameter gives us information about the collision, including the object was hit (in collision.gameObject). As you can read in the documentation, a rigidbody is required for it to work.

What we are doing here is that when a bullet hits an alien, we use GameObject.Destroy() to remove both the bullet and the alien from the scene. Since the script is running on the bullet, this.gameObject refers to the bullet, and collision.gameObject refers to the alien.

You can now press Play to test this in Unity. Press Space to fire, and when a bullet hits an alien, both should disappear.

There's just one thing that we haven't handled, however: what happens to bullets if they don't hit the alien? As it is, they just keep on accumulating:

Notice the long list of Bullet(Clone)s in the Hierarchy panel. To get rid of bullets that have gone out of view, the easiest way is to just destroy them when they go beyond a certain distance. In the Update() method of the Bullet script, you can add something like this:

        if (this.transform.position.y > 4.8f)

Awesome! :D In this article, we have handled collisions so that bullets are able to destroy aliens. The game is taking shape.

However, there are still a lot of things we need to do:
  1. Allow the player to move sideways
  2. More aliens
  3. Aliens should move downwards when reaching a side of the game area
  4. Aliens should shoot at the player
  5. There should be a cooldown for firing bullets (e.g. you can only fire one bullet every second)
  6. We need a welcome screen before the game begins
  7. We need a main menu
  8. We need to transition to other levels when all enemies are cleared
  9. We need to show some kind of score
As you can see, creating a game can involve a lot of work, and much of game design is tweaking things until the game feels right and is fun! :)

In tomorrow's last article in the Ranch Invaders series, we will cover the first few points in order to have a single playable level. We will be covering the remaining points as well, but not as part of the Ranch Invaders series!

Thursday, May 30, 2013

Unity3D: Space Invaders (Part 3 - Prefabs)

Hello, and welcome back to the Ranch! :)

This article continues with the Ranch Invaders series. However, like with yesterday's article, if you haven't read the previous articles, you can simply follow along by creating a new Unity project.

In today's article, we're going to add the player's ship into the game, and allow it to shoot bullets. In doing this, we will learn what prefabs are, and how to create objects while the game is running.

From the GameObject menu, go to Create Other -> Sphere. In the Hierarchy section, select the Sphere, press F2, and rename it to "Player". Move it so that it appears in the bottom of the camera's view (you might want to select the Main Camera to see its preview while you do this).

Next, from the GameObject menu, go to Create Other -> Capsule. Rename it to "Bullet". After pressing the 'R' key to go into scaling mode, resize the bullet (capsule) so that it is much smaller than the player (sphere).

Your work so far might look something like this:

Now, from the Hierarchy panel, drag the Bullet into the Assets panel:

The result is that the Bullet is added to the Assets panel, and in the Hierarchy panel, its entry turns blue. This means that the Bullet is now a prefab.

The Player and the Alien objects are simply objects in the scene. Since the Bullet is a prefab, we can refer to it in scripts and create as many Bullets as we like through code. A great thing about prefabs is that you can customise the prefab once (e.g. make a bullet with a yellow material), and all instances of that prefab will have the same features. Let's see how this works in practice.

In the Assets panel, right click somewhere, and in the context menu, select Create -> Material. Name it "Bullet". In the Main Color property, select whichever colour you think is best for a bullet (e.g. yellow). Drag the material onto the Bullet object either in the Hierarchy panel or in the world view:

Right click the Assets panel and Create -> C# Script. Name it "Bullet". Drag the script onto the Bullet object. Double-click the script to launch MonoDevelop.

In the Bullet class, add a public variable to represent the speed:

    public float speed = 1.0f;

When you expose a public variable like this, it appears in the Inspector in the section where the script is:

You can now change this variable as you like through the Inspector, and when you Play the game in Unity, that value will be used. Note, however, that if you change such variables while Playing, changes will be reverted once you stop playing.

Now, we need to write a script that will take care of the bullet's movement. Since we're doing Sp-- sorry, Ranch Invaders, we're looking to do something like this:

The bullet starts at the player's position, and is shot upwards where the Aliens will be. In code, we can do this as follows:

public class Bullet : MonoBehaviour
    public float speed = 1.0f;
    private Vector3 target;
    // Use this for initialization
    void Start ()
    { = this.transform.position + new Vector3(0, 20, 0);
    // Update is called once per frame
    void Update ()
        Vector3 currentPosition = this.transform.position;
        Vector3 newPosition = Vector3.MoveTowards(currentPosition,, speed * Time.deltaTime);
        this.transform.position = newPosition;

Remember that we're going to have the Player create (shoot) bullets. When the bullets are created, they will be at the Player's position. We want the bullets to go upwards, so we define a target that is a certain distance away (e.g. 20 units). By adding a Vector3(0, 20, 0) that simply points directly upwards, to the initial bullet position, we can set a destination for the bullet that is directly above its starting position.

In the Update() method, we use Vector3.MoveTowards() which works pretty much like Lerp (see yesterday's article). Except that instead, we are moving the Bullet from its current position towards the target in steps of speed * Time.deltaTimeTime.deltaTime is a measure of frame time, so the bullet will move a short length upwards with every frame. We multiply speed to be able to control the speed.

From the Unity editor, press the Play button and watch the bullet move upwards. If you think it's too fast or too slow, tweak the speed by selecting the Bullet and changing the speed value in the Inspector.

You can now delete the Bullet from the scene. Since it's among our Assets, we can create it at runtime. Create a new C# script called "Player" and drag it onto the Player object. Double-click the Player script to open it in MonoDevelop.

In the Player class, add the following public variable:

    public GameObject bullet;

Save the script. Back in Unity, select the Player object, and in the Inspector, under the Player Script, notice that there is now a slot for the bullet game object:

From the Assets panel, drag the Bullet prefab into the appropriate slot in the Inspector, where it currently says "None (Game Object)".

Now, from the Player script, we can make instances of this prefab. In the Update() method of the Player script, just add the following:

        if (Input.GetKeyDown(KeyCode.Space))
            Instantiate(bullet, this.transform.position, Quaternion.identity);

So all we're doing here is that when the player presses the Space key, we use the Instantiate() method to create a bullet. We give it the object we want to instantiate (in this case the bullet prefab), and its starting position and orientation (rotation). I'm not going to go into quaternions here, but Quaternion.identity simply means that the bullet isn't rotated.

You can now press Play to try out the game. Press Space to watch bullets move like sausages in the sunset:

If it doesn't work, don't worry! :) Depending on how you carried out the steps above, it is possible that the bullet prefab wasn't saved correctly. In my case, for example, I found that the Bullet script was missing. Since a prefab is really just a template for an object, you need to make sure that any changes to it apply to all the objects that use that template. So in the case of the missing script, once you drag the Bullet script onto a Bullet object in the scene, you need to click "Apply" at the top of the Inspector in order to apply the changes to all affected objects.

Great! We can now shoot sausage-like bullets to our heart's content. We still have some work left to do, though: we need more aliens, the player's ship needs to move sideways, bullets need to destroy aliens, etc. We'll handle some of these things in the next article. Until then, au revoir! :)

Wednesday, May 29, 2013

Unity3D: Space Invaders (Part 2 - Linear Interpolation)

Hi all! :)

In the previous article ("Unity3D: Space Invaders (Part 1 - Navigation and Materials)"), we began working on a Space Invaders clone called Ranch Invaders. Today we're going to continue where we left off, and we're going to animate the alien moving around. If you didn't follow the previous article, don't worry! :) All you need to do is start a new Unity project and drag a cube onto the scene.

If you've read "Unity3D: Moving an Object with Keyboard Input", you might remember that in order to make an object behave in some way, we need to attach a script to it. So, right-click in the Assets panel, and in the context menu, select Create -> C# Script. You can call it Alien (or whatever you like). Then, drag the script onto the Alien object (cube). You'll know you've done it right when you select the Alien object and the Alien script appears in the Inspector:

Double-click the Alien script to open it in MonoDevelop. You are presented with a default (empty) behaviour script:

You will notice that these scripts all inherit from a MonoBehaviour class and have at least Start() and Update() methods. The Start() method allows us to set certain variables when the object is initialised, while the Update() method is called continuously while the game is running. A game is interactive because it shows (renders) a certain number of images (frames) per second. The Update() method is called every frame. So that is where you put most of your logic. Note: there are other, similar methods if you need more control, but we don't need to get into those right now.

In "Unity3D: Moving an Object with Keyboard Input", we saw that we could set an object's position by assigning a new Vector3 to its transform.position:

        this.transform.position = new Vector3(5, 5, 5);

However, what we'd like to do is have the Alien move gradually from one point to another. You can think of it like this:

So we want the Alien's x-position to start at -5, and move gradually to the right until it reaches x=5. With each frame, x is set to a different intermediate value t.

First, we need a variable to store the time when the animation began. Add this variable in the Alien class:

private float startTime;

The float data type is something we haven't covered in the C# articles so far, but it's simply a number that may have a decimal value (e.g. 5.48). When assigning float values, we need to add an 'f' suffix to the value (e.g. 5.48f).

Next, we set this startTime to the current time in the Start() method:

    void Start ()
        this.startTime = Time.time;

Unlike float, which is a standard data type, Unity uses its own classes to represent time. Instead of the DateTime type we're used to from C#, Unity has its own Time class. The equivalent of DateTime.Now is Time.time, and it gives us a float representing the current time.

We can now change the Update() method as follows to carry out the animation:

    void Update ()
        float t = Time.time - startTime;
        float x = Mathf.Lerp(-5.0f, 5.0f, t);
        this.transform.position = new Vector3(x, 5, 5);

Remember that Update() is called every frame. Thus, based on the current time, we calculate how far along the animation we have come, and store it in t. We can then use Lerp() to set x to the correct intermediate value between -5.0f and 5.0f.

Before I mess up your mind with an explanation on Lerp, press F8 to make sure the code compiles, and then press Play from within Unity. Watch the Alien (cube) move gradually from left to right. This will help you understand better what is happening.

Lerp is short for linear interpolation, which might sound like some scary monster. But to understand it, refer again to this diagram:

Let's say t starts at 0, and goes up to 100 as time goes by. It's not the same as the value of x; think of it as a percentage.

Now, let's say that at a particular point in time, t is 0.6 (60%). In order to find the corresponding value of x, we need the value that marks 60% of the way between -5 and 5. That's

t starts at zAs time goes by, t increases. To keep it simple, let's say it increases in whole numbers. So from -5, it becomes -4, -3, and so on until it finally reaches 5. The x value can be calculated from t as follows:

In Unity, you don't really need to worry about the mathematics. Just keep track of the time, and store the elapsed time in a variable (such as t). To use the Lerp() method, just pass the minimum, maximum, and t values as parameters, in that order. The result is the intermediate, or interpolated value you want.

When you press Play in Unity, you'll notice that the Alien (cube) moves across rather quickly. You can regulate this by multiplying a speed value:

        float t = (Time.time - startTime) * 0.4f;

The value (in this case 0.4f) is up to you to choose. Values less than 1 will make the cube move more slowly, and values greater than 1 will make it move faster.

Wonderful! :) In this article, we learned how to use linear interpolation (lerp) to animate the movement of a cube. As a matter of fact, interpolation is used in all sorts of animation, from video game credits scrolling vertically, to an object gradually changing colour when it is hit by a bullet. A lot of this functionality can be used easily using libraries such as iTween, but learning how it actually works gives you much more control.

Come back for the next article in the Ranch Invaders series, in which we will learn about prefabs and use them to shoot bullets! In the meantime, as an exercise, implement the code that allows the alien to move from left to right, down, right to left, down, etc (see this video to get an idea). :)

Monday, May 27, 2013

Unity3D: Space Invaders (Part 1 - Navigation and Materials)

Hello, fellow game developers! :)

In today's article we're going to start working on a clone of the arcade classic, Space Invaders. To prevent Tomohiro Nishikado from suing my ass off, we'll instead call this Ranch Invaders. Through this game we'll learn a number of important concepts including prefabs, linear interpolation, materials, and more. Since we can't learn all this in a single article, this will be spread out over several articles.

If you've been following my previous Unity3D articles, the last project you used will automatically open when you launch Unity. Create a new project from File menu -> New Project... and find a place to put it:

You don't need to import any packages. Once Unity relaunches with your new project, press Ctrl+S to save your .unity (scene file) somewhere.

Great. Now, we'll begin working on the alien, and we'll use it to learn some basics about working with Unity. For the time being, we'll use a simple cube as the alien, so go to GameObject menu -> Create Other -> Cube, just the same as we did in the previous two articles. You should now have a cube sitting in your game world (left portion of the screen):

You can see from the Inspector that the cube is at (0, 0, 0). You will also notice three arrows (red, green and blue) shown on the cube in the game world. You can click and drag one of the arrows to move the cube, and you will see the Position values in the Inspector change. You can also drag one of the squares between the arrows in order to move the cube in two directions (e.g. X and Y) at once.

In the Hierarchy section, there's also an object called Main Camera apart from the Cube you placed. If you select it, you'll see a little preview window:

If you press the Play button at the top of the Unity interface, you'll see the same thing. The main camera represents what the player is seeing.

Select the Cube again. Using the mouse, you can navigate the scene in order to work with the objects in it. If you press Alt and click and drag the left mouse button, you can rotate the view around the currently selected object (the Cube in our case). A middle-click (click the mouse's scroll wheel) and drag pans (moves sideways) the view relative to the selected object. By scrolling the mouse wheel, you can zoom the view towards or away from the camera. Finally, you can use the gizmo at the top-right of the world view to view the scene from particular directions (e.g. from the top).

You can manipulate the object itself by moving, rotating, or scaling it. We have already seen how to move an object (by using the arrows). You can use the W, E and R keys (or the buttons at the top-left of the Unity interface, just below the File menu) to switch between movement, rotation and scaling mode. When you do this, the arrows will change:

The screenshot above shows how the arrows change when you are scaling. You can drag one of the coloured boxes to scale in one direction, or the small box at the centre in order to scale uniformly (in all directions). Rotation has yet another thingy you can drag in order to rotate in different directions.

Once you're comfortable with navigating the scene using these controls, it's time to customise our Alien (Cube) a little bit.

With the Cube selected in the Hierarchy panel, press F2 and rename it to Alien.

Next, right click on the Assets panel and select Create -> Material. Name it Alien as well. Click on the white box next to "Main Color" and select whatever colour you want your alien to be:

Drag the material from the Assets panel onto the cube in the world view:

Other than using a solid colour, you can also select an image that you think would make it look more like an alien. To do this, right click in the Assets panel, select Import New Asset... and find the image you want on your filesystem. Once the image appears in your Assets panel, you just need to select the Alien's material and drag the image into the area that says "None (Texture)":

That's about as alien-like as it can get. This technique of wrapping an image around a 3D object is called texturing, and the image is called a texture.

Great! :) We covered some basic navigation controls in this article, as well as how to apply a material to a 3D object. The material may be either a solid colour or an image (texture).

In the next article, we will learn about linear interpolation, and use it to script the alien's sideways-moving behaviour. Until next time! :)

Sunday, May 26, 2013

Unity3D: Setting up Source Control with SVN

Hi all! :)

Any experienced developer will tell you that source control using something like SVN is important for anything but the simplest projects. Source control allows you to keep a complete history of any changes you made, download them to different machines (great when working with other people on the same project), compare different versions of source files, and even revert to a specific version when necessary.

This article assumes you are already familiar with SVN, and are using a client such as TortoiseSVN. If you have no clue at this point, you can safely skip this article - future articles will not depend on it.

Start a new project and insert a cube into the game world via GameObject menu -> Create Other -> Cube, just so we have something in the game world.

Press Ctrl+S to save a .unity file into your project's Assets folder. This .unity file is called a Scene file - you can have several different scene files for different views such as the main menu, credits screen, and actual gameplay.

Now that you have something small in your project, you might want to commit it into SVN. The problem is that in your project's Library folder, there is this metadata folder with loads of weird subfolders:

...and each of those subfolders has a bunch of weird files:

Given that there are loads of such files and folders, and that they change very frequently, maintaining these in SVN will be a nightmare.

Fortunately, however, there is another way to use SVN with Unity.

From the Edit menu, go to Project Settings -> Editor. The Editor Settings will appear in the Inspector, on the right. From here, change the Version Control Mode from Disabled to Meta Files.

In Windows Explorer, navigate to your project folder:

Close Unity. The Temp folder will disappear.

Next, delete the Library folder. Don't worry - this will be created with the new meta files format (instead of all those weird files and folders) next time we open Unity.

You can now commit the project folder into SVN. If you're using TortoiseSVN, right click on the project folder, and select TortoiseSVN -> Add... and select all files and folders in the project. Then, right click the project folder and select SVN Commit... to commit the project into SVN:

Now, re-open the project in Unity by double-clicking the .unity file in your project's Assets folder. In the status bar at the bottom-left, you will see a message saying "Rebuilding Library because the asset database could not be found!":

Finally, to prevent you from accidentally committing the Library or Temp folders while you work, add both folders to the SVN ignore list by right-clicking on each folder and selecting TortoiseSVN -> Add to ignore list -> [Library/Temp]:

Once you have done this, the Temp and Library folders should carry an appropriate icon showing that they are excluded:

You can now continue making changes in Unity and committing them to your heart's content.

I hope that this was useful, and that you'll check back for other articles on Unity3D and on programming in general! :)

Friday, May 24, 2013

Unity3D: Moving an Object with Keyboard Input

Hi! :)

Today we're going to take a first look at the Unity3D game development engine. This engine is pretty easy to use and has gained a lot of popularity in recent years. It supports multiple languages (including C#) and multiple operating systems (including PC, Mac, Linux. Android, iOS, and others). Therefore, aside from Programming on Linux with MonoDevelop, this is one other way you can use C# on non-Windows platforms. You will learn in this article that Unity actually uses MonoDevelop anyway.

The first thing you will need to do is to download and install Unity from their website.

Once you have installed it and gone through the initial registration screens (you should normally opt to use the free version if you're just learning), you will be asked to open or create a new project:

In the "Create New Project" tab, select a folder where your project will be created. You do not need to import any packages for this tutorial.

You are then taken to the Unity interface, and shown a welcome screen. You can close the welcome screen. From the Layout drop-down menu at the top-right, select "Tall" to switch to a different layout.

Next, from the GameObject menu, select Create Other -> Cube to place a cube into the game world.

The cube will now be listed in the Hierarchy section - this section shows you a list of objects in your game world. You can also see the objects in the game world itself, in the left portion of the screen. If you click on the cube, you can see its properties (e.g. position in the game world) in the Inspector:

The Inspector shows information about the game object, such as its position in the game world. You can move it around by either changing values in the Inspector, or dragging the coloured arrows drawn over the object in the game world.

Underneath the Hierarchy section, you have a Project section. Right click on the Assets panel in the right-hand-side of the Project section and create a new C# script:

The script appears under Assets. Call the script "Movement". Then, double-click the script to edit it. When you do this, MonoDevelop (bundled with Unity) opens as the default editor:

In the Update() method, add the following code:

        if (Input.GetKeyDown(KeyCode.LeftArrow))
            Vector3 position = this.transform.position;
            this.transform.position = position;

What are we doing here? In Unity, you can attach scripts to objects in order to make them do stuff. In our case, we will attach this script to the cube to be able to move it with the arrow keys.

The "this" in a Unity script refers to the object that the script is attached to (e.g. the cube). Each object has a transform property, which contains stuff like its position in the world. The position consists of a Vector3 which contains the x-, y- and z- coordinates of the object in the world.

The code above simply makes the object move left when the left arrow key is pressed, by varying the x-coordinate of the object's position. While it would normally make sense to modify x directly, you can't do that in Unity. Also, note that we are using different code from previous articles (such as "C#: ASCII Art Game (Part 1)"), because Unity has its own classes to handle this sort of stuff.

In MonoDevelop, press F8 to make sure that the code compiles. Then, switch back to Unity. Drag the Movement script onto the Cube object in the Hierarchy section. Once you click on the Cube in the Hierarchy section, you should see the Movement script in the Inspector:

Now, Press the Play button at the top of the Unity interface to start playing. The world view changes into an interactive rendering of the game:

Test the game by pressing the Left Arrow key. Doing this should move the cube to the left:

Press the Play button again to stop the game. In MonoDevelop, update the code to handle movement in all four directions:

        if (Input.GetKeyDown(KeyCode.LeftArrow))
            Vector3 position = this.transform.position;
            this.transform.position = position;
        if (Input.GetKeyDown(KeyCode.RightArrow))
            Vector3 position = this.transform.position;
            this.transform.position = position;
        if (Input.GetKeyDown(KeyCode.UpArrow))
            Vector3 position = this.transform.position;
            this.transform.position = position;
        if (Input.GetKeyDown(KeyCode.DownArrow))
            Vector3 position = this.transform.position;
            this.transform.position = position;

Press Play again in Unity to test it. Note that the cube returned to its original position. That is because each time you press Play, a new session is started with all objects having their default values.

Great! :) In this article, we learned about the Unity interface, and wrote a small script to move a cube in the game world. I have intentionally skipped certain details (e.g. navigation in the game world), as they will be covered in other articles. So check back later! :)

Wednesday, May 22, 2013

C#: Programming on Linux with MonoDevelop

Hello everyone! :)

C# is a language invented by Microsoft, and is normally used to create applications on Windows, using Visual Studio or, less commonly, SharpDevelop.

But as a matter of fact, it is also possible to write C# applications on Linux! There is a development environment similar to SharpDevelop, called MonoDevelop, which supports Linux development.

On a Debian-based system such as Kubuntu, you would open a terminal and install MonoDevelop using the following command:

sudo apt-get install monodevelop

If you have another flavour of Linux (e.g. based on Red Hat), you will need to use the appropriate package manager instead (e.g. rpm).

You can now launch MonoDevelop either by typing monodevelop in the terminal and pressing ENTER, or by finding it among your particular Linux distribution's applications (in the case of Kubuntu, via the K-menu).

From here, click Start New Solution... (see above).

Select "Console Project" from under C#. As with Visual Studio or SharpDevelop, you need to specify a name for the solution, and where you would like it to be created.

The next screen (above) is a bit weird. Just skip it by pressing the "OK" button.

You have now created your little console project, and MonoDevelop gives you sample code for a typical "Hello world" program. Press F5 to try and run it...

Well, that's not quite what we were expecting, right? We have a System.InvalidOperationException saying that "File name has not been set", but we have no clue how to fix it. Fortunately, though, someone has already bumped into this before, and the solution is simply to install xterm:

sudo apt-get install xterm

Once you install xterm, restart MonoDevelop. You can now debug your program to your heart's content:

Woohoo! :) This brief article showed you how to set up MonoDevelop on a Linux environment, and compile a basic application. You should now be able to go through just about any article at Programmer's Ranch so far using MonoDevelop if you like.

Note, however, that MonoDevelop can't do everything. For example, at the time of writing, it is simply not possible to get any WPF application working on Linux. However, MonoDevelop has some interesting alternatives such as Gtk# which I have yet to explore.

Happy coding, and stay tuned for more tutorials! :)

C# Basics: Building Strings

Hullo! :)

In yesterday's article, C# Network Programming: Simple HTTP Client, we built an HTTP request (in a String variable) and sent it out over the network.

We built the String as a literal string. That is just one of several ways to build complex Strings. In this article, we will look at a few other techniques we could have used instead.

Method 1: Literal Strings

As a refresher, in yesterday's article we created a literal String like this:

             String request = @"GET / HTTP/1.1
Connection: Close


The @ character before the String denotes it as a literal. If you remove it, the program won't compile.

Literal Strings allow you to include newlines. A simple Console.WriteLine(request); allows you to see how the above code is translated:

Method 2: Escape Sequences

You can also include newlines by using the \r and \n escape sequences as follows:

 String request2 = "GET / HTTP/1.1\r\nHost:\r\nConnection: Close\r\n\r\n";

\r is a carriage return (ASCII #13) and \n is a line feed (ASCII #10); these two characters together make up a newline. There are several other of these escape sequences, all starting with a backslash (\) followed by a particular character, but these two are by far the most useful.

The disadvantage of this approach is that if you have a particularly long String (and HTTP requests are usually quite a bit longer than this), the code isn't very readable.

Method 3: String Concatenation

You can build up a long String from smaller Strings using concatenation (+ operator):

            String request3 = "GET / HTTP/1.1\r\n";
            request3 += "Host:\r\n";
            request3 += "Connection: Close\r\n\r\n";

You still need escape sequences, since this is not a literal String. However it's a bit more readable than having one long String.

While concatenating one or two small Strings is okay, this becomes very inefficient when you have a lot. This is because in C#, Strings don't change: you aren't really adding one String to another. You are in fact creating a third String made up of both of them.

Method 4: StringBuilder

The solution to the problem of String concatenation is to use the StringBuilder class. This is great for when you need to build a long String out of a lot of smaller ones. For this you first need to include:

using System.Text;

Then, just do something like this:

            StringBuilder request4Sb = new StringBuilder();
            request4Sb.Append("GET / HTTP/1.1\r\n");
            request4Sb.Append("Connection: Close\r\n\r\n");

The text here is only converted to a String when you use the ToString() method:

            String request4 = request4Sb.ToString();

This means that you can do a lot of String manipulation before that in an efficient way.

Method 5: Format Strings

You can use String.Format() to build up Strings using the familiar {0} notation we've been using all along in our calls to Console.WriteLine():

             String request5 = String.Format("{0}\r\n{1}\r\n{2}\r\n\r\n",
                "GET / HTTP/1.1""Host:""Connection: Close");

This is most useful when you have a number of variables that you want to swap into the Strings. Like with Console.WriteLine(), you can include those variables as parameters, and refer to them using {0}, {1}, etc.

In this case, there is not much use in using String.Format(), since all the Strings involved are well-known constants. It even looks pretty ugly.

But the fact remains that String.Format() is another useful way to build complex Strings.


In this article we have seen five different ways of building Strings, and compared them to each other.

In the case of a simple HTTP request, using a literal String is no doubt the best way, both for efficiency and for code readability.

In other scenarios, however, other techniques may prove to be more suitable.

Thanks for reading, and come back for more! :)