Sunday, 21 August 2016
Static,Static Variables,Static Functions
Static
The static keyword is a keyword that ties all instances of a class together. This allows all instances of a class to share a common variable or function. When you see static next to a function, this means you don’t need to make a new instance of the class to use it. Because static functions and variables are class-wide, we access them in a slightly different way than an instance of a variable or function. There is a static function found inside of Input called GetKey(), which we will use. The last keyword is bool, after public and static. We’ve seen bool before, but this is used as a return type. When we write our own functions, we’ll also include our own return type, but just so you know, return types are not limited to bool. Functions can return any data type, and now we’ll take a look at how this all works.
A Basic Example
Let’s start with the Static project; begin by opening the scene in the Unity 3D Assets Directory. The Main Camera in the scene should have the Player component attached.
AKey UnityEngine.Debug:Log(Object) Player:Update () (at Assets/Player.cs:15)
The KeyCode class has a public variable for each key on your computer’s keyboard. Each variable returns true when the key on the keyboard is pressed. The Input.GetKey() function returns the bool value based on which the key is checked in the KeyCode class. We assign the bool AKey to the returned value from the Input.GetKey(KeyCode.A); function. The statement if (AKey) then executes the Debug.Log("AKey"); which then prints out AKey to the Unity Console window. The GetKey() function is a member of the Input class and is accessed by using the . or dot operator. Now that we’re reading libraries we need to know how to get to the members of the classes we’re looking at.
//image
Select the GetKey() and go to the definition of this function. You can do this by right clicking on the word and selecting Go To Definition in the pop-up. This will open the Assembly Browser, where we’ll be shown the function’s definition. We’re shown public static bool GetKey(KeyCode key) as the function’s definition. This process provides us with the beginnings of a player controller script. Filling in the rest of the WASD keys on the keyboard will allow you to log the rest of the most common movement keys on your keyboard. The Input class is found in UnityEngine that was included in this class with the using UnityEngine directive at the top of the class.
From previous chapter lessons, you might imagine we’d need to create an instance of Input to make use of its member functions or fields.
This might look like the following:
//image
When we check for any functions in the MyInput object after it’s been instanced, we won’t find any- thing useful. The only things available are universal among all things inheriting from the object class. We’ll get to what the object class is in Section 6.13.4, about inheritance, but for now, just assume that these functions will appear and act the same for pretty much anything you are allowed to make an instance of. The lack of functions or variables is due to the fact that all of the functions and variables have been marked as static, so they’re inaccessible through an instance of Input. Statically marked functions and variables become inaccessible through an instance. This inaccessibility is related to an object’s interface and encapsulation. This doesn’t mean that they are completely inaccessible, however; but to see them, we’ll need to write our own class with our own functions and variables.
Static Variables
Let’s start off with a simple concept: a static variable. Using our previous analogy of toasters, each new toaster built in a factory has a unique identity. Each unit built would have a different serial number. Once in someone’s house, the number of times the toasters have been used, when they are turned on and begin to toast, and their location in the world are all unique to each toaster. What they all share is the total number of toasters that exist. The static keyword means that the function or variable is global to the class it’s declared in. Let’s make this clear; by declaring a variable as static, as in static int i;, you’re indicating that you want to use the int i without needing to make an instance of the class that the variable is found in.
Variables that are unique to each instance of a class are called instance variables. All instances of the class will share the static variable’s value regardless of their instanced values. If we create a mob of zombies, we might find it important to maintain a certain number of zom- bies. Too many and the computer will have problems keeping up. Too few and the player will go around with nothing to shoot at. To give ourselves an easier time, we can give each zombie a tele- pathic connection with all other zombies. A programmer would call this a static variable or a static function. As we’ve seen, variables usually live a short and isolated life. For instance, the variable used in the ever-powerful for loop exists only within the for loop’s code block. Once the loop is done, the variable in the for loop is no longer used and can’t be accessed outside of the loop.
Now that we’re creating objects based on classes, we need to make those classes interact with one another in a more convenient way. To keep track of the number of undead zombies in a scene, we could have the player keep track; as each zombie is created or destroyed, a message could be sent to the player. The Player class keeping track of important zombie data is awkward. Zombie-related data should remain in the zombie class, unrelated classes should not depend on one another in this way. The more spread out your code gets, the more problems you’ll have debugging the code.
Creating self- contained classes is important, and prevents a web of interdependent code, sometimes referred to as spaghetti code. Remember that when an object is created it’s instanced from a single original blueprint, which can include some variables that are shared between each instance of the class. With static variables instanced cases can talk to the blueprint for a common connection between any new instances made from it.
Static Functions
Static functions act on behalf of all instances of the class they are a member of. They work only with static variables of the class. If we extend our zombie class with a new static function, we can use the zombie
class to call a static function that can read static variables. To make the static function accessible to other classes we need to make the static function public as well.
Then we’ll add a call to Zombie.CountZombies(); to find out how many zombies have been created in the Update () function of the Player class, by adding it to the if(AKey) code block.
Now when the A key on the keyboard is pressed, we’ll get a count printed to the Console panel indicating the number of zombies in the scene along with the Debug.Log("AKey"); console log.
//image
The 4 being printed out comes from the public static void CountZombies(); function call being made to Zombie, not from any of the instances of the zombie class attached to the capsules in the scene. To call static functions, you use the class name, not the name of an instanced object made from the zombie class. As you can see, there’s more than one way the class identifier is used. Up to this point, we’ve been using the class name mostly as a way to create an instance of that class. With a static function or variable, the class identifier is used to access that static member of the class.
The static keyword is a keyword that ties all instances of a class together. This allows all instances of a class to share a common variable or function. When you see static next to a function, this means you don’t need to make a new instance of the class to use it. Because static functions and variables are class-wide, we access them in a slightly different way than an instance of a variable or function. There is a static function found inside of Input called GetKey(), which we will use. The last keyword is bool, after public and static. We’ve seen bool before, but this is used as a return type. When we write our own functions, we’ll also include our own return type, but just so you know, return types are not limited to bool. Functions can return any data type, and now we’ll take a look at how this all works.
A Basic Example
Let’s start with the Static project; begin by opening the scene in the Unity 3D Assets Directory. The Main Camera in the scene should have the Player component attached.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
//Use this for initialization
void Start ()
{
}
//Update is called once per frame
void Update ()
{
//add in a check for the A key bool AKey = Input.GetKey(KeyCode.A);
if (AKey)
{
Debug.Log("AKey");
}
}
}The code here will send the following to the Console panel in Unity 3D.
AKey UnityEngine.Debug:Log(Object) Player:Update () (at Assets/Player.cs:15)
The KeyCode class has a public variable for each key on your computer’s keyboard. Each variable returns true when the key on the keyboard is pressed. The Input.GetKey() function returns the bool value based on which the key is checked in the KeyCode class. We assign the bool AKey to the returned value from the Input.GetKey(KeyCode.A); function. The statement if (AKey) then executes the Debug.Log("AKey"); which then prints out AKey to the Unity Console window. The GetKey() function is a member of the Input class and is accessed by using the . or dot operator. Now that we’re reading libraries we need to know how to get to the members of the classes we’re looking at.
//image
Select the GetKey() and go to the definition of this function. You can do this by right clicking on the word and selecting Go To Definition in the pop-up. This will open the Assembly Browser, where we’ll be shown the function’s definition. We’re shown public static bool GetKey(KeyCode key) as the function’s definition. This process provides us with the beginnings of a player controller script. Filling in the rest of the WASD keys on the keyboard will allow you to log the rest of the most common movement keys on your keyboard. The Input class is found in UnityEngine that was included in this class with the using UnityEngine directive at the top of the class.
From previous chapter lessons, you might imagine we’d need to create an instance of Input to make use of its member functions or fields.
This might look like the following:
void Update ()
{
Input MyInput = new Input();
bool AKey = MyInput.GetKey(KeyCode.A);
Debug.Log(AKey);
}While this syntactically makes sense, you’re better off not creating new instances of the Input class. The GetKey() function is static, so there’s no need to create an instance of Input to use the function. This will make more sense once we write our own static function later in this chapter. However, should we actually try to use MyInput as an object, we’d have some problems.
//image
When we check for any functions in the MyInput object after it’s been instanced, we won’t find any- thing useful. The only things available are universal among all things inheriting from the object class. We’ll get to what the object class is in Section 6.13.4, about inheritance, but for now, just assume that these functions will appear and act the same for pretty much anything you are allowed to make an instance of. The lack of functions or variables is due to the fact that all of the functions and variables have been marked as static, so they’re inaccessible through an instance of Input. Statically marked functions and variables become inaccessible through an instance. This inaccessibility is related to an object’s interface and encapsulation. This doesn’t mean that they are completely inaccessible, however; but to see them, we’ll need to write our own class with our own functions and variables.
Static Variables
Let’s start off with a simple concept: a static variable. Using our previous analogy of toasters, each new toaster built in a factory has a unique identity. Each unit built would have a different serial number. Once in someone’s house, the number of times the toasters have been used, when they are turned on and begin to toast, and their location in the world are all unique to each toaster. What they all share is the total number of toasters that exist. The static keyword means that the function or variable is global to the class it’s declared in. Let’s make this clear; by declaring a variable as static, as in static int i;, you’re indicating that you want to use the int i without needing to make an instance of the class that the variable is found in.
Variables that are unique to each instance of a class are called instance variables. All instances of the class will share the static variable’s value regardless of their instanced values. If we create a mob of zombies, we might find it important to maintain a certain number of zom- bies. Too many and the computer will have problems keeping up. Too few and the player will go around with nothing to shoot at. To give ourselves an easier time, we can give each zombie a tele- pathic connection with all other zombies. A programmer would call this a static variable or a static function. As we’ve seen, variables usually live a short and isolated life. For instance, the variable used in the ever-powerful for loop exists only within the for loop’s code block. Once the loop is done, the variable in the for loop is no longer used and can’t be accessed outside of the loop.
for (int i = 0; i < 10; i++)
{
print(i);//prints 1 to 10
} //i no longer exists
print(i);//error, i is undefined
Now that we’re creating objects based on classes, we need to make those classes interact with one another in a more convenient way. To keep track of the number of undead zombies in a scene, we could have the player keep track; as each zombie is created or destroyed, a message could be sent to the player. The Player class keeping track of important zombie data is awkward. Zombie-related data should remain in the zombie class, unrelated classes should not depend on one another in this way. The more spread out your code gets, the more problems you’ll have debugging the code.
Creating self- contained classes is important, and prevents a web of interdependent code, sometimes referred to as spaghetti code. Remember that when an object is created it’s instanced from a single original blueprint, which can include some variables that are shared between each instance of the class. With static variables instanced cases can talk to the blueprint for a common connection between any new instances made from it.
Static Functions
Static functions act on behalf of all instances of the class they are a member of. They work only with static variables of the class. If we extend our zombie class with a new static function, we can use the zombie
class to call a static function that can read static variables. To make the static function accessible to other classes we need to make the static function public as well.
using UnityEngine;
using System.Collections;
public class Zombie : MonoBehaviour
{
static int numZombies; //int numZombies;//no longer static
//Use this for initialization
void Start ()
{
numZombies++;
Debug.Log(numZombies);
}
//Logs number of zombies to the console
public static void CountZombies()
{
Debug.Log(numZombies);
}
}
Then we’ll add a call to Zombie.CountZombies(); to find out how many zombies have been created in the Update () function of the Player class, by adding it to the if(AKey) code block.
using UnityEngine;using System.Collections;public class Player : MonoBehaviour
{
//Use this for initialization
void Start ()
{
}
//Update is called once per frame
void Update ()
{
//add in a check for the A key bool AKey = Input.GetKey(KeyCode.A);
if (AKey)
{
Debug.Log("AKey"); //calls the static function in Zombie
Zombie.CountZombies();
}
}}
Now when the A key on the keyboard is pressed, we’ll get a count printed to the Console panel indicating the number of zombies in the scene along with the Debug.Log("AKey"); console log.
//image
The 4 being printed out comes from the public static void CountZombies(); function call being made to Zombie, not from any of the instances of the zombie class attached to the capsules in the scene. To call static functions, you use the class name, not the name of an instanced object made from the zombie class. As you can see, there’s more than one way the class identifier is used. Up to this point, we’ve been using the class name mostly as a way to create an instance of that class. With a static function or variable, the class identifier is used to access that static member of the class.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment