In this post, we will be looking at some frequently asked questions about Unity and 2D shooters and 2D Games (in general).

You can detect keystroke by using the function Input.GetKey. For example, the following code detects when the key E is pressed; this code should be added to the Update function.

To play a sound, you need to add an Audio Source component to an object; when this is done, you can either play its default audio clip, or select which audio clip should be played.

To display text onscreen you will need to create a UI Text object, and then access it through a script. For example:

How can I ensure that a projectile will not be subject to gravity?

If a projectile includes a Rigidbody2D component, you can make sure that it is not subject to gravity by setting its gravity scale attribute to 0.

To set a projectile in movement, you need to apply a force to it. For example, to move it up the screen, the following code could be used.



<< Back to top





You can use the function called Random.Range to create a random number; for example, the following code will create a number between -10 and +10.

You can use a timer that can determine from when and for how long a variable should have a specific value; the timer can start at 0 and then increase until it has reached a specific threshold; when this is the case, a new value can be set for the variable. The following code snippet illustrates how this can be done.

void Update() { timer+=Time.deltaTime; float threshold = 5.0f; if (timer > thresold) { ... } }



<< Back to top





Accessing Resources

Where should I store assets if I want to access them from a script?

You can create a folder called Resources, and then save your imported assets in this folder.

How can I access a text file that I have saved in the Resources folder?

To access this file (and the text within) you can use the following code snippet.

TextAsset t1 = (TextAsset)Resources.Load("words", typeof(TextAsset)); string s = t1.text;

How can I access an image file that I have saved in the Resources folder?

To access an individual sprite from the Resources folder, you can use the following code snippet.

Sprite s1 = (Sprite) (Resources.Load(nameOfCard));

However, if you’d prefer to access and save several sprites at once, then you can use the following snippet:

Sprite[] allSprites = Resources.LoadAll("lion");



<< Back to top





Detecting users inputs

How can I detect keystrokes?

You can detect keystrokes by using the function Input.GetKey. For example, the following code detects when the key E is pressed; this code should be added to the Update function.

If (Input.GetKey(KeyCode.E)){...}

How can I detect a click on a button?

To detect clicks on a button, you can do the following:

Create an empty object.

Create a new script and link it to this object.

Select the button in the Hierarchy .

in the . Using the Inspector , click on the button located below the label called OnClick .

, click on the button located below the label called . Drag and drop the empty object to the field that just appeared.

From the Inspector, You should then be able to select the function that should be called in case the button is clicked.

How can I detect drag and drop actions on an image?

To detect drag and drop actions on an image:

Select the image from the Hierarchy .

from the . Using the Inspector , add a component called Event Trigger ( Component | Event | Event Trigger ) to this image.

, add a component called ( ) to this image. In the component Event Trigger, click on the button called Add New Event Type (as illustrated in the net figure) and then choose the option called Drag or End Drag from the drop-down menu.



<< Back to top





Networking

What is the difference between a client and a server?

In computer science terms, a server provides services that may be requested by clients. So usually clients would connect to the server to avail of a service. In terms of web development, a server will deliver a page or execute a programme (e.g., script) and provide the output to a client (e.g., through a client browser). In a networked game, and for the particular case of a FPS, the server will host the entire game, and the client will connect to the server to access the game, and to also avail of any update in the game, so that all players have a synchronized version of the game world; in other words, we want all clients to see the same version of the world in which they play. So the client and the server, once connected, will exchange information. Because of the amount of information involved and possible bandwidth challenges, there is a balance to be reached between updating the server regularly and also keeping running the game smoothly with no or little delay.

What is the difference between a public and a private address?

Servers that use public address can be accessed directly from the Internet because there is no firewall between the client and the server. A firewall would typically restrict access to the devices on its network (e.g., clients or servers) and hide the actual IP address of these also. However, a server can also use a private address; this is usually the case when the server is installed behind a firewall. By default, in Unity, if the server is hosted on your own computer, the address of the server will be, in most cases, 127.0.0.1, which, in computer terms, usually defines your own computer (i.e., localhost).

How can I make sure that an object is networked?

All objects to be networked will need to have a NetworkIdentity component. If you would like the position of this object to also be tracked, then a NetworkTransform component may also need to be added.



<< Back to top



Accessing databases

How do I run a PHP script?

A PHP scrip needs to be executed by a server, so it needs to be hosted on a server and then accessed through its address (i.e., url). These scripts are usually saved in the public folder of the web server.

How do I access a database using PHP?

To access a database in PHP you need a server name (or address), a user name, a password, the name of a database, along with the name of the table that you need to access. In the next code snippet, you should be able to see how a connection is initiated in PHP through a function called connect; the function mysql_connect is employed to establish a connection to a server, based on settings such as: the name of the server, the name of the database to be accessed, a user name, and its password.

function connect() { $host="localhost" ; $database="mydatabase"; $user="user1"; $password = "mypassword"; $error = "Cant connect"; $con = mysqli_connect($host,$user,$password); mysqli_select_db($con, $database) or die("Unableto connect to database"); }

Do I need to host my pages on a website to run PHP scripts or to create a database?

While an online server is a common solution, you can also download and install AMP and run the server on your own computer for testing purposes; AMP packages (MAMP or WAMP for example), include a web server, as well as MySQL, so that you can also create and access a databases hosted on your own computer, if need be.

In terms of accessing a database, what does the term localhost mean?

Localhost, when used within a PHP file, refers to the server where the PHP script is stored; so if the script is stored on your computer, and you have a local server, then the localhost will be the web server on your computer; however, if these files are hosted on a remote server, then this remote server will be the localhost in this case.

What is the link between Unity, PHP, and MYSQL?

When accessing a MYSQL database through Unity, the process is usually as follows: (1) Unity accesses a PHP page, this page contacts the database and performs actions (e.g., read or write); (2) in case data is read, this data is stored in the PHP script, and then sent back to Unity from this script.

What are SQL statements?

SQL statements can be used to perform a query on a database; they are set of instructions used to perform actions such as: selecting, ranking, reading or writing to records.

Why is there a need to set privileges for a database?

When you create an online (or local) database, you usually want to restrict access to it so that only admin users can modify it. This is so that the database is not changed by mistakes, or to avoid possible malicious and unauthorized changes to the database.





<< Back to top



Reading Files

What is XML?

XML stands for eXtensible Markup Language. It was originally designed to store data in a way that could be easily readable by both humans and computers; these files use the extension .xml and have a common structure that makes them easy to read by humans. An XML file includes a succession of nested elements (or nodes) delimited by their tags. Each element also includes attributes.

What does the term IEnumerator mean?

The term IEnumerator, when added before the name of a method, defines this method as a co-routine; this means that if, within this function, we wait for an external event (e.g., obtaining a file from a website), the system will move on, and come back to this function whenever the data has arrived; so by adding IEnumerator to a method, we give the game the ability to carry-on with other tasks while a method may need some more time to collect the data that it needs to resume its tasks.

How is the class XMLDocument used for XML files?

The class XMLDocument can be used to instantiate objects that will represent the content of an XML file; this class also provides methods to make it easier to access the corresponding file and to read the content within, often using an XPATH syntax to access the nodes. For example, in the next code snippet, the XMLDocument is used to create an object doc, that will store the content of an XML file.

XmlDocument doc = new XmlDocument ();

How can I read the content of a text file from Unity?

You can store this file in a folder named Resources, and then read its content as follows:

TextAsset t1 = (TextAsset)Resources.Load("maze", typeof(TextAsset)); string s = t1.text;

How can I read the content of an image (the color of each pixel)?

To read the pixels from an image at the position (x, y), you can use the method GetPixel, as demonstrated in the next code.

Color[,] colorOfPixel; public Texture2D outlineImage; colorOfPixel= new Color[outlineImage.width, outlineImage.height]; colorOfPixel[x, y] = outlineImage.GetPixel(x, y)

How can I generate content procedurally?

There are many ways of generating content procedurally; some of these include reading content from a file and then creating objects accordingly. These files can range from plain text-based files, to XML documents, or images. In each case, the content is read, and depending on the values (and/or attributes within), a specific object is created.



<< Back to top





Optimization

Why should I optimize my game?

Optimizing your code can make a great difference in the way your game is perceived (and appreciated) by the players. By minimizing bottlenecks and increasing the speed of the game, you can make sure that the player will have a smooth experience.

What can I do to identify bottlenecks in my game?

The first port of call is the Profiler, as it will identify methods (and code in general) that may require too many resources (e.g., milliseconds or garbage collection).

How can I reduce bottlenecks?

Some of the best things that you can do to make sure that your game will run smoothly include: decreasing garbage collection, reducing computer-intensive code for methods that are called often, reducing the number of instantiations, making sure that empty magic methods are deleted, making sure that scripts are not added twice to an object, and avoiding boxing and unboxing as much as possible.

What are the main differences between the heap and the stack?

The stack is used for local variables; it is relatively fast to access and its memory management is rather simple. The stack is used for classes and objects, its memory management is slightly more complex and helped by the garage collector; accessing the heap is relatively slower than the stack.

What non-code based solutions can I use to improve my game’s performances?

Before optimizing your code, you could ensure that you: use prefabs as much as possible, compress audio when possible, use texture atlases, or apply occlusion culling and different levels of detail, especially if the scene includes many objects that could be occluded easily.