Game Development Reference
In-Depth Information
Listing 10-19 shows a case where an object can access and edit the private variable of another
instance, as freely as if it were its own variable.
Listing 10-19. Accessing a private variable
public class MyClass
{
private string Name = "DefaultString";
void TestFunction()
{
MyClass C = new MyClass();
C.Name ="ah ha";
}
}
This happens because the privacy variable obtains between
classes
and not
instances
. Multiple
instances of the
same class
can access each other's private variables. Thus, private variables are
inaccessible
only
to instances of different classes.
goto is C# Teleportation
There's one statement in programming that nearly every programmer seems to dislike. It's been
termed “bad practice” and has received such wide condemnation that it's easy to wonder why
newer languages like C# even added the feature in the first place. That feature is the infamous
goto
statement (pronounced
go to
), which allows program execution to suddenly divert from its normal
course and jump to a different, specified location in the source file. Thus, it's a kind of teleport
feature. Some people recommend never using
goto
at all, because its teleporting nature obfuscates
code, making it difficult to follow and understand. And yet, in moderation,
goto
can prove useful and
sometimes cleaner for breaking out of loops early (see Listing 10-20).
Listing 10-20. Using goto
void Search(int Index)
{
int[,] IntArray = new int[4, 2] { { 2, 2 }, { 5, 5 }, { 5, 1 }, { 2, 8 } };
for(int i = 0; i < IntArray.GetLength(0); i++)
{
for (int j = 0; j < IntArray.GetLength(1); j++)
{
if (IntArray[i, j].Equals(Index))
{
goto Found;
}
}
}
Found:
Debug.Log("GameObject Found");
}