5 Common Coding Errors in C# and Unity and how to Solve them

As you will start your journey through C# coding, you may sometimes find it difficult to interpret the errors produced by Unity in the console. However, after some practice, you will manage to recognize them, to understand (and also avoid) them, and to fix them accordingly. The next list identifies the errors that my students often come across when they start coding in C#.

When an error occurs, Unity usually provides you with enough information to check the location of this error in your code, so that you can fix it. While many are relatively obvious to spot, some others are trickier to find. In the following paragraphs, I have listed some of the most common errors that you may come across as you start with C#. The trick is to recognize the error message so that you can understand what Unity is trying to tell you.

Again, this is part of the learning process, and you WILL make these mistakes, but as you recognize these errors, you will learn to understand them (and avoid them too :-)).

Again, Unity is trying to help you by communicating, to the best that it can, where the issue is with your code; so by understanding the error messages, we can get to fix these bugs easily. To make it easier to fix errors, Unity usually provides the following information when an error occurs:

  • The name of the script where the error was found.
  • The location of the error (i.e., row and column).
  • A description of the error.

So, if Unity was to generate the following error message…

“Assets/Scripts/MyFirstScript.cs (23,34) BCE0085: Unknown identifier: ‘localVariable’”

…it is telling us that an error has occurred in the script called MyFirstScript, at the line 23, and around the 34th character (or the 34th column) on this line. In this particular message, it is telling us that it can’t recognize the variable localVariable.

So, you may come across the following errors; this list is also available in the resource pack as a pdf file, so that you can print it and keep it close by:

  1. “;” expected: This error could mean that you have forgotten to add a semi-colon at the end of a statement. To fix this error, just go to the line mentioned in the error message and ensure that you add a semi-colon at the end of the statement.
  2. Unknown identifier: This error could mean that Unity does not know the variable that you are mentioning. It can be due to at least three reasons: (1) the variable has not been declared yet, (2) the variable has been declared but outside the scope of the method (e.g., declared locally in a different function), or (3) the name of the variable that you are using is incorrect (i.e., spelling or case). Remember, the names of all variables and functions are case-sensitive; so by just using an incorrect case, Unity will assume that you refer to another variable.
  3. The best method overload for function … is not compatible: This error is probably due to the fact that you are trying to call a function and to pass a list of parameters (which means the number and the types of parameters) that is not compatible with what the function is expecting. For example, the method mySecondMethod, described in the next code snippet, is expecting a String value for its parameter; so, if you pass an integer value instead, an error will be generated.
void mySecondFunction(string name)

{

print (“Hello, your name is” +name);

}

mySecondFunction(“John”);//this is correct

mySecondFunction(10);//this will trigger an error

  1. Expecting } found …: This error is due to the fact that you may have forgotten to either close or open curly brackets for conditional statements or functions, for example. To avoid this issue, there is a trick (or best practice) that you can use: you can ensure that you indent your code so that corresponding opening and closing brackets are at the same level. In the next example, you can see that the brackets corresponding to the start and the end of the method testBrackets are indented at the same level, and so are the brackets for each of the conditional statements within this function. By indenting your code, using several spaces or tabulation, you can make sure that your code is clear and that missing curly brackets are easily spotted.
Void testBrackets()

{

if (myVar == 2)

{

print ("Hello World”);

myVar = 4;

}

else

{

}

}


  1. Sometimes, although the syntax of your code is correct and does not yield any error in the Console window, it looks like nothing is happening; in other words, it looks like the code, and especially the methods that you have created do not work: This is bound to happen as you create your first scripts. It can be quite frustrating (and I have been there :-)) because, in this case, Unity will not let you know where the error is. However, there is a succession of checks that you can perform to ensure that this does not happen; so you could check the following:

    • The script that you have written has been saved.
    • The script contains no errors.
    • The script is attached to an object.
    • If the script is indeed attached to an object and you are using a built-in method that depends on the type of object it is attached to, make sure that the script is linked to the correct object. For example, if your script is using the built-in method OnControllerColliderHit, which is used to detect collision between the FPSController and other objects, but you don’t drag and drop the script on the FPSController object, the method OnControllerColliderHit will not be called if you collide with an object.
    • If the script is indeed attached to the right object and is using a built-in method such as Start, or Update, make sure that these functions are spelt properly (i.e., exact spelling and case). For example, for the method Update, the system will call the method Update every frame, and no other function. So if you write a method spelt update, the system will look for the Update function instead, and since it has not been defined (or overwritten), nothing will happen, unless you specifically call this function from your code. The same would happen for the method Start. In both cases, the system will assume that you have created two new functions update and start.



    Click here if you want to know more about learning to code in C# in less than 60 minutes.

Creating, activating or destroying objects

Instantiating and Casting

Using C# through Unity, you will at some point, need to create (or instantiate) new GameObjects; this can be done in several ways; the first way could be to call the constructor of the class GameObject as in the next code.

GameObject g = new GameObject ();

Another way, is to use the built-in function called Instantiate. So, for example, let’s say that we want to instantiate bullets, that we have created as prefabs; we could use the following code:

public GameObject bullet;

void Start ()

{

GameObject g3 = (GameObject)(Instantiate (bullet, transform.position, Quaternion.identity));

In the previous code:

  • We instantiate a new object and save it in the variable g3.
  • We use the method called Instantiate to create a new Object; this method takes three parameters: an object, a position and a rotation.

Now, the important thing to notice here is that the method Instantiate returns a variable of type Object and NOT GameObject; however, when we create the variable g3, we need to make sure that, because the type of g3 is GameObject, that what is returned by the method Instantiate is also of type GameObject; this is the reason why we use the code (GameOBject) just before the keyword Instantiate: this is called Casting; by casting, we have converted the type returned by the method Instantiate from Object to GameObject.

You will obviously use Csting in other occasions; however, when using the Instantiate method, we will need to use casting.

Note that casting can be done using the keyword as, as described in the following code:

GameObject g3 = Instantiate (bullet, transform.position, Quaternion.identity) as GameObject;

In the previous code we use the key words as GameObject to specify that the Object returned by the method Instantiate will be casted as a gameObject.

Destroying

As we have seen previously, it is possible to instantiate objects using the Instantiate function; and it is also possible to destroy or to deactivate an object accordingly.

To destroy a specific object, you can use the Destroy function and destroy an object either instantaneously or after a specified delay, as illustrated in the next code snippet.

void Start ()

{

Destroy (gameObject, 5);

Destroy (GameObject.Find ("Cube");

}

In the previous code:

  • We use the function Start.
  • We destroy the object linked to this script with a delay of 5 seconds; this could be used for example, for bullets or any objects that would typically disappear a few seconds after its creation. Note that we use gameObject with a lowercase g as we refer to the object linked to this particular script.
  • In the second line, we look for an object called Cube and we destroy it instantaneously.

There are also times where it is good not to destroy an object, but instead, to deactivate it; for example, you may want an object to appear in the scene only after the player has collected some items; this can be useful for treasure hunts, or adventure games based on exploration; in this case you would typically do the following:

  • Add the object to the scene manually (possibly). While you could do this through code, doing this manually has the advantage, especially for bulky object, to know exactly where and how they will fit in the scene. Of course, if you had to do this for several objects, a script-based Instantiation may be more efficient.
  • Make sure the object is activated in the Scene view (by checking the Inspector)
  • Create a reference to the object in your script before it is deactivated.
  • Deactivate the object from your script at the start of the scene.
  • Reactivate the object from your script when an event has occurred (e.g., player collected all relevant items).
public class DestroyAndDeactivate : MonoBehaviour {

GameObject g;

bool collectedItems;

void Start ()

{

g = GameObject.Find ("Cube2");

g.SetActive (false);

}


void Update ()

{

if (collectedItems && ! g.activeInHierarchy) g.SetActive (true);

}

In the previous code:

  • We declare the variable g that will be used as a reference to the object we need to hide/deactivate.
  • We also declare a Boolean variable that will be used to know whether the necessary items to activate the object have been collected.
  • Then, in the function Start, we find the object called Cube2 and link it to the variable g.
  • Through the variable g, we deactivate the object Cube2.
  • In the Update function, we then check that the object Cube2 is not active; we also check that the items have been collected; if this is the case, then we activate the object Cube2.

So this approach is very useful when you want to reveal or unveil some items; and you can also, as we have seen earlier, destroy objects either instantaneously or after a delay.

Deactivating

This being said, there are cases when you may want to make sure objects (and any related component or children) are not destroyed when transitioning between scenes. You see, when you load a new scene, by default all the objects in the previous scene are destroyed before the objects from the new scene are instantiated. So, there are cases

 

In this case, you could use the following snippet and attach the corresponding script to the object that you’d like to keep between scenes.

void Awake()

{

DontDestroyOnLoad(transform.gameObject);

}

In the previous code:

  • We implement the method called Awake that is usually called when the script is loaded; this method is called only once in the lifetime of the game.
  • We then use the method DontDestroyOnLoad to ask Unity to keep this particular object and its children.
  • The method Start in not used in this case, as it is often called every time a scene is starting; however, in our case, we just want to call it once in the game, and Awake is therefore more appropriate.

 

You could this method when you want to create a game manager that should be present in (accessible from) any scene, for example.

Transforming, following, and accessing objects (and their children)

Introduction

In this post we will be looking at how effectively use Transforms in you code to be able to implement some interesting (and much needed) effects and features including: translations, rotations, and animations.

Continue reading

Mapping Object Oriented Principles to C# with Unity & Syntax

 

In Unity, when using C# to create your game, you will be writing statements and creating new classes in C# following an object-oriented programming syntax. However, compared to the usual Object Oriented programming practices, Unity’s syntax may seem different, at first glance, even to seasoned developers. So this post will help you to compare and see how Object Oriented concepts can be used with Unity.

Continue reading

School Bundle (i.e., site license) ending this Thursday

From September onward, a “School Bundle” will be made available to schools and universities; the idea is to make the books and videos more accessible to students.

As a teacher, you will be able to enroll your class or school to the “School Bundle”; all students will then have access to all my books (the ones that I have published) in pdf format, as well as all the videos currently available on learntocreategames.usefedora.com plus any additional course or video, for 12 months.

 

See more here…

Creating an Infinite Runner


In this post, we will start by creating an infinite runner game, a classic game genre on mobile devices; this game will have the following features:

  • The player will have to avoid obstacles by jumping above them.
  • Jumps will be performed when the player presses a key (for the web versions) or when s/he taps once on the right side of the device’s screen (for the Android version).
  • The obstacles will come from the right side of the screen.
  • If the player hits one of the obstacles, the game will be restarted.

  Continue reading

Free PDF Sample Chapters for 7 books on Unity Today.

You can now access a free pdf sample of any of the book published on this website.

ztp_foundationsztp_intermediate ztp_beginner ztp_advanced 2d_platform_kindle 2d_shooter_kindle abgt_puzzle

So far, this list includes 7 books on Unity that teach a wide range of very handy Unity skills (i.e., 2D shooter games, 2D puzzle games, 2D platform games, AI, networked games, collision detection, animation, audio, 2D games, etc); they also provide introductions to C# and JavaScript programming.

If you have been considering some of these topics  you can now download the first chapters of any these books for free today and see how they can help you to create games; here is how:

– Open this page.
– Select a book (i.e., click on it).
– On the new page, select the link “Free Book Sample”.
– Click on the button labelled Checkout; this will take you to a FREE Checkout page where you just have to enter your email address to receive the pdf sample.

That’s it.

PS: If there is a topic that should be covered, please leave a note/comment.

Save

Save

Creating a simple word game

In this section, we will create a word guessing game with Unity, with the following features:

  • A word will be picked at random from an existing list.
  • The letters of the word will be hidden.
  • The players will try to guess each letter by pressing a letter on their keyboard.
  • Once a letter has been discovered it will then be displayed onscreen.
  • The player has a limited number of attempts to guess the word.

So, after completing this tutorial, you will be able to:

  • Read words from a text file.
  • Pick a random word.
  • Process and assess the letters pressed by the player.
  • Display the letters that were correctly guessed by the player.
  • Track and display the score.
  • Check when the player has used too many guesses.

figure1

Figure 1: The final game

Continue reading