Graphics Reference
In-Depth Information
Private static
A private static variable exists within the class it was declared and in any other
instances of the same class . Other classes/types of script will not be able to access
it.
As a working example, try to imagine that a script named player.cs directly
controls player objects in your game. They all need to tell a player manager script
when something happens, so we declare the player manager as a static variable in
our player.cs script like this:
private static PlayerManager playerManager;
The playerManager object only needs to be set up once, by a single instance of the
player class, to be ready to use for all the other instances of the same class. All
player.cs scripts will be able to access the same instance of the PlayerManager.
4. The singleton design pattern.
In the previous part of this section, we looked at using a static variable to share a
manager script across the entire game code. The biggest danger with this method
is that it is possible to create multiple instances of the same script. If this happens,
you may find that your player code is talking to the wrong instance of the game
controller.
A singleton is a commonly used design pattern that allows for only one instance
of a particular class to be instantiated at a time. This pattern is ideal for our game
scripts that may need to communicate (or be communicated with) across the entire
game code. Note that we will be providing a static reference to the script, exactly
as we did in the “Static Variables” method earlier in this section, but in implement-
ing a singleton class, we will be adding some extra code to make sure that only one
instance of our script is ever created.
1.1.3 Using the Singleton Pattern in Unity
It is not too difficult to see how useful static variables can be in communication between
different script objects. In the public static example cited earlier, the idea was that we had
a game controller object that needed to be accessed from one or more other scripts in our
game.
The method shown here was demonstrated on the Unity public wiki* by a user named
Emil Johansen (AngryAnt). It uses a private static variable in conjunction with a public
static function. Other scripts access the public function to gain access to the private static
instance of this script, which is returned via the public function so that only one instance
of the object will ever exist in a scene regardless of how many components it is attached to
and regardless of how many times it is instantiated.
A simple singleton structure:
public class MySingleton
{
private static MySingleton instance;
public MySingleton ()
* http://wiki.unity3d.com/index.php/Singleton.
 
Search WWH ::




Custom Search