[Help] How the code is being read

OK guys i’m at S02 - 20 i’ve done everything correctly and my code is working exactly as the ones in the videos, but in this lesson i didn’t quite understand what happened, so in this lesson the Number Wizard is going to start to guess the number for this we used the following code :

 	if( Input.GetKeyDown( KeyCode.UpArrow ) )
	{
      min = guess;
      guess = ( max + min ) / 2;
      print (guess);
    }

and the parameters for this code where set before void Start (){} as

int max = 1000;
int min = 1;
int guess = 500;

After you press the down key one time you get the result 750 that i completely understand, what i can’t figure out how it works is when you press the up arrow for the second time.

When you press the arrow the second time you get the result 875 witch is the calculus to 750 + 1000 / 2 witch is fine, the program is getting the print (guess) and using it as the new guess instead of the parameter guess = 500 but that is what i don’t quite understand isn’t the int guess = 500 the value he should be getting ? And so how does the program knows that we should use the print (guess) in the guess = min ?

here is the full code if some one wants to see it :

http://pastebin.com/FTM3B0V3

Hi @Fernando_Fernandes,

Those variables (fields) are set at the class level, therefore, when they are updated, they are updated at the class level.

Thus, min = 1 only at the beginning. After that, when you press the up arrow, you are changing the value of min to the last guess. It then takes another guess using the new value.

Does this make sense?

Fernando…

When you define a variable or an object at the top of a script class and outside any method these variables default to being public variables so that any class outside of the defining class can get access to. This is the case when using C# with Visual Studio and the .NET Framework as well as when working with MonoDevelop and the MonoDevelop Framework, which is an equivalent of the .NET Framework.

When Unity3d itself needs access to such script declarations, the lectures demonstrate this by defining such variables at the top of a script class.

However, there is a drawback to these types of simpler explanations in the lectures since they are being made as easy to understand as possible. This drawback is the lack of understanding of a property of declarations and methods we call “scope”. “Scope” defines the capabilities of how variables and methods can be seen within only a module, a solution, or outside of a solution. This sounds more complex than it is. And to make it simple, let us stay with just variable declarations…

In C# there are 4 primary variable scopes, which are called “access modifiers”, that can be used…

  • public
  • private
  • internal
  • protected

Each of these modifiers should precede the variable type in a variable declaration. So for example, if we were to define a public variable of type string with a name of “myString” it would appear as such…

public string mystring = "";  // we initialize the variable to a string that contains no data;  this is NOT null

In Unity3d, the C# scripting that you will write will in essence function the same way as the C# used in a .NET web application; In both cases you are writing classes that will always be subordinate to the overriding application. In .NET web applications, the overriding application is that of Internet Information Server or IIS. In Unity3d development, the equivalent application is always the Unity3d engine.

You will write as many C# classes as you require to make your game functional based on your requirements. All of these classes will default to being “public” since the Unity3d engine requires access to them. This is done by default and you can see this every time you define a new class in MonoDevelop for your game development. Simply look at the modifier that precedes the new class definition in the source code. In Visual Studio, the framework simply uses the default with no modifier.

Within every class you create for Unity3d you will define variable and object declarations. Each of these declarations defined outside of any method (functions or procedures; a function returns a value, a procedure does not… ie. “void”) will default to being “public”.

A “public” declaration means that what is being defined can be seen by any method within the class that contains the declaration, any other class in your project solution, as well as the Unity3d engine, both of which are external to this class. By making such declarations “public” you allow the Unity3d engine to interact with these declarations as you have seen in the various lectures.

HOWEVER, it is always a “best practice” to always provide the variable modifier with your variable declaration. Not doing so means that you are allowing for the default to take its place. Though this is correct coding, it makes the coding ambiguous and should be avoided.

There are two other types of variable scoping that will be used in your C# classes for Unity3d; at least in the learning phases of your studies. These scope types are “private” and “local”.

A “private” variable declaration in a class and defined outside of any method can be seen by any method in the class but not outside the class; in this latter case by the other classes in your project solution and the Unity3d engine. By the way, you can NEVER define a class as “private”.

You can define either a “public” or “private” variable anywhere in a C# class and their corresponding scoping will always apply. This means that you can define such variables at the top of a class, in its middle, or at the bottom.

HOWEVER, it is “best practice” to always define such declarations at the top of a class as practically all developers do.

It is also a “best practice” to use as few “public” declarations in a class as possible and only define those that are actually required. This is a standard 'best practice" for both proper coding techniques but just as importantly for security concerns whereby you limit the amount of exposure of each class to the outside world.

The last type of declaration modifier we have is that of “local”. HOWEVER, there is no actual scope modifier that can be applied here as it is always the default in such cases.

“Local” declarations are defined WITHIN a METHOD or a BLOCK of code. For example, a “local” declaration in a method would look like the following…

private void MyMethod() {

     int MyInteger = 0;
}

For a block it would like the following…

for (int x = 0; MyInteger < 10, MyInteger++) {

}

In both cases, the variable, “MyInteger” can only be seen within the method or the block of the for-loop. As a result, if you attempt to use “MyInteger” anywhere else in the class but within the “scope” of where it was defined, the compiler will give you an error.

The compiler will also give you warnings if you define “MyInteger” as both a “private” and “local” declaration; the first being outside of any method, the other within a method. What will happen here is that the compiler will warn you of ambiguity with your variable declarations.

The “internal” and “protected” modifiers are used for more advanced coding techniques when declaring variables and objects.

An “internal” modifier allows you to make a declaration that allows you to expose your variables or classes only to other classes within your solution. So if you create 5 C# classes and make one of the classes “internal” instead of “public”, the other 4 classes in your project solution will be able to see the classes but Unity3d will not. Subsequently, for these other 4 classes to work with the internals of your “internal” class, you will have to define your variables, objects, and methods that you wish to expose to these other 4 classes as “internal” as well.

The “protected” modifier is only used when dealing with inheritance hierarchies. However, historically this modifier has caused more trouble than it is worth as it has destroyed many an inheritance hierarchy by making them to rigid, This modifier allows only an inherited class to see the declarations with a modifier of “protected”.

Despite the hoopla made over inheritance hierarchies, which were made very popular in the 1990s and early 2000s, such programming has often been the bane of many a project because the project designers did not know what they were doing. If you do find yourself in need of working with inheritance make sure you keep such hierarchies as small as possible and avoid using the “protected” modifier.

For more definitive information on scope and declaration modifiers, see the following… Modifiers (C# Reference)

Steve

This is quite a reply @Steve.Naidamast, especially for the Number Wizard section!

Only if their Access Modifier is set to public, the default behaviour for C# is private, so you would be able to use them within the class itself, but they won’t be seen externally to that class unless the access modifier is changed.

This is done by default and you can see this every time you define a new class in MonoDevelop for your game development. Simply look at the modifier that precedes the new class definition in the source code. In Visual Studio, the framework simply uses the default with no modifier.

The classes are actually created from a template, which is changeable should you ever need to, for example, you could update the template and enter the access modifier private in front of both Start() and Update() methods.

By the way, you can NEVER define a class as “private”.

Private classes can actually be defined within another class (nested classes) - considerably outside the scope (excuse pun) of Number Wizard though!


See also;

Hi Rob… :slight_smile:

As to the definition of class variables defaulting to “private” that is not the case with the courses being given by Ben. He defines his class variables without any modifiers and they are being seen by the Unity3d engine. However, you are correct and I was in fact wrong on this since I never use defaults to the point I have no idea what they are anymore and have to look them up.

I also come from the Visual Studio environments where things may be slightly different. Like other posters have said, I have seen these things change from one version to the next with Visual Studio and the .NET Framework.

You are also correct in that you can define a class as private but as you noted that is only within another class to my understanding. If you defined a class as private in general, nothing could see it in a solution. And in Visual Studio as far as I know this cannot be done without getting compiler errors.

Steve

Hi Steve,

He defines his class variables without any modifiers and they are being seen by the Unity3d engine.

Only accessible within that class though, as they are defaulted to private. In order to have them visible to the Inspector they would need to be set as public. Anywhere else within the game/application, static.

Do you happen to have the specific lecture number for this so I can check?

If you defined a class as private in general, nothing could see it in a solution.

Absolutely

And in Visual Studio as far as I know this cannot be done without getting compiler errors.

That is also correct;


Private class within a class example;

Note, I have never had the cause to use anything like this!

public class Class1
{
    Class2 otherClass;
    public Class1()
    {
        otherClass = new Class2();
    }

    public void SetOtherClassText(string text)
    {
        otherClass.SetStoryText(text);
    }

    public string GetOtherClassStoryText()
    {
        return otherClass.GetStoryText();
    }

    // private class
    private class Class2
    {
        string storyText;   // defaults to private

        public void SetStoryText(string text)
        {
            storyText = text;
        }

        public string GetStoryText()
        {
            return storyText;
        }
    }
}

Rob… :slight_smile:

My apologies. I stand corrected…

I looked through my script modules and saw that the public variables were given the access modifier of “public”.

I have taken 80 lectures in the space of around 2 weeks so I admittedly was getting a little confused as to what I was remembering from the earlier script modules.

Hey Steve,

It’s no biggy, we are all here to learn :slight_smile:

I would love someone to give me a useful example of where I might want to use a private class, I can think of a few reasons, but at the same time they all seem overly complicated and utterly unnecessary - and not related to a game - hehe :slight_smile:

I have taken 80 lectures in the space of around 2 weeks

That’s some serious investment of time, well done! I look forward to playing some of your implementations of the course games, as and when you want to share, and anything else you create yourself too! :slight_smile:

Hi Rob…

Many developers have often taken the use of class development as part of a larger picture for their use in inheritance hierarchies. This outlook was quite popular in the 1990s as OOP development became increasingly a part of all programming projects. Others looked at class development to support the popular theory of reuse, though this concept has been thoroughly discredited by a number of software engineering analysts. Reuse then requires the development of generic classes that are basically static in nature. Since such development is most often highly difficult to accomplish and can only be applied to a limited number of situations, the concept of reuse eventually drifted into obscurity.

However, when I began studying OOP many years ago, the text I was using also provided a history of its original development in Sweden (I believe) with the Simula-67 language. As a result I took away a completely different perception for the development of object oriented programming. My interpretation was that it was primarily designed for more accurate and cleaner organization of applications that had become too monolithic.

As a result, though I agree with your questioning as to why anyone would create a private class in a parent class module, I believe you could define some limited purposes for its inclusion in such a development paradigm. For example, what if you were developing a complex class that could use the organization of several mini-classes that only the parent classes methods would ever need? Instead of using arrays for the data or comma-delimited strings, you may instead want to use classes or in fact, structures, to temporarily store your data that the parent class uses.

In highly complex development such as with financial applications or medical applications, such a use of private classes could be of value. I worked in the financial industry for about half of my 42 years in the corporate environments. And I saw a lot of terrible programming that could have used far superior OOP approaches. I also saw a lot of complexity whereby internally declared private classes may have helped. However, as developers we most often consider the separate, individual class as the common denominator in all such development.

Even with Unity, as the coding becomes more complex, developers may actually find a use for internal, private classes to organize their code better.

As to my own game design plans, they are somewhat limited. I have little interest in a lot of the game development that I see going on today. I find it either too violent and\or too often too much emphasis on realism where there shouldn’t be since so many younger people can become desensitized to the world around them by the types of games being produced currently. I mean, do we really want young people engaging in nothing but violent depictions of warfare? I don’t believe the sociological results have shown any positive nature to any of this.

My interest is in simulation programming of historical battles since I am also a military historian and flight simulation (I have always loved WWI aviation history); the latter a colleague and I are trying to develop to bring a new era of interest in WWI combat aviation.

As a result, it will probably be quite a while before I can finally demonstrate anything…

Most of what I am studying now has little to do with my ultimate interests but I am using these lessons to provide me with a way to learn the Unity environment in-depth while also keeping an eye out for what I can take away from such training for my own purposes.

Privacy & Terms