When do you use a variable as a type?

So I think I understand using States as a type. I’ve seen it done mainly when accessing another script. So if I have a script named EnemyController, I can do something like:

public EnemyController enemyScript;

enemyScript = FindObjectOfType<EnemyController>();

So then I’m just wondering what the occasions are for when you have to use a variable name as a type? I know I can just make it public and drag an object over in the editor, but it seems there are situations when you can’t do that, such as with the enumerator.

My working theory is whenever you have to access data from another variable, or when it is it’s own type. I know that an enum is it’s own data type apparently, so is that why, or is it because we have to access all of the data it contains?

Hi,

Just wanting to check I understand your question correctly, do you mean, when do you expose variables via the Inspector, over finding the game object in code?

Not exactly, I’m pretty sure I understand public and private. The only times it matters which it is is when you need to make it public to edit it in the editor, or you need to make it private to keep it in a particular script. Right?

What I was asking was how you know when to use a variable you’ve created as it’s own type. For example in the text game the enum goes:

private enum theGameStates {1, 2, 3, 4};
private theGameStates currentState;

So the name for the enum variable was used as it’s own type when creating the variable to store the enum’s values. I would never have guessed that and would have tried to make “currentState” a string. In my other example above, the name of the script I’m referencing, “EnemyController” is used as it’s own type to store the reference as well.

My question is, is there a way to know when the variable type should be the name of another variable or object, or do you just have to learn these things as you go along?

Hi,

The only times it matters which it is is when you need to make it public to edit it in the editor, or you need to make it private to keep it in a particular script. Right?

Close…

Private and Public (and there are others too) are known as access modifiers, they indicate the scope of a class, variable (field), property, method. In layman’s terms, access modifiers restrict access of the thing to other things.

You should be aware that this isn’t a Unity thing, it relates in this case to C#.

When you set the scope of a class to be public you are enabling pretty much everything to be able to “see” it, and thus interact with it. If it is only something that returns a value that may be ok, but what if your class was used in a payroll system, and the variable you have just set as public was the salary. Potentially, other code/applications could access this, someone may be able to see all of the salary’s for staff in an organisation when ordinarily, this wouldn’t be possible.

However, in the specific case of Unity, yes, if you want to expose a variable so that it can be interacted with within the Unity editor then setting it to public will achieve that, but it isn’t the only way. You can also make a variable private, limitiing its scope and enable it to be manipulated within the Inspector. I have provided a link below for you which covers this.

As a rule of thumb, it’s typically better practice to restrict everything initially and then when it comes to a scenario where you need to access the value of a member variable of a class, have a good think about why. Is there an alternative rather than directly accessing a variable.

In your enum example, the variable name is currentState, this could have been anything at all but obviously makes sense to name it inline with what it is or represents. The actual enum has been named theGameStates, it’s a little bit of an odd one really, as by default an enum will represent an integer if no other type has been specified. So your theGameStates enum really returns an int.

Regarding the specific question;

My question is, is there a way to know when the variable type should be the name of another variable or object, or do you just have to learn these things as you go along?

You need to consider what the type of data you are dealing with. So, starting with a few obvious examples;

  • I want to store a series of characters so that I can display them to the screen. I would use a string.
  • I want to store the number of lives a player has, lives are a whole number, thus, I would use an int.

string and int are predefined types, classes you create yourself you can name as you wish, again, keeping these relavent to what they represent is typically the best approach, as per the EnemyController. That class definition defines a type called EnemyController. You could declare a variable, of any name, of that type, for example;

EnemyController controllerOfTheEnemies;

controllerOfTheEnemies.ResetPositions();

In the above, the type is first, followed by the variable name, I could have called it Fred…

EnemyController fred;

fred.ResetPositions();

as you can see, it would work the same way, just makes very little sense! Where-as perhaps this;

EnemyController enemyController;

enemyController.ResetPositions();

…just reads that little bit more nicely and as such makes more sense.

Does this help?


See also;

Okay so I looked it up and realized that I might be thinking of User-Defined Types of Custom Types. I found a doc from Mircrosoft, linked below where it mentions you can use “struct, class, interface, and enum constructs to create your own custom types.”

So does that mean that enum is one of the few times you can do this sort of thing? With the EnemyController example, it’s a class and we’re using it as it’s own type, and you can’t really do that with other types such as a string.

Hi,

Sorry for delay responding.

I’m not entirely sure I understand the question, could you elaborate a little further.

Okay, I realize that I forgot to add the link, and I don’t even remember where it was. Let me see if I can ask a clearer question.

So if I want to access a variable in another script, say a boolean called “jumpFlag” in a script called “PlayerController,” I can do it like this:

public PlayerController playerScript;

if (playerScript.jumpFlag == true)
{
    //something happens
}

I made a type of “PlayerController.” I made a type out of the name of the script. The same happens with the enum, where the name of the enum becoming the type of variable that holds the enum values.

An integer holds whole numbers. Strings hold text values, and booleans hold either true or false. But what kind of data does a PlayerController type hold? What do you call types made from the names of other objects? Can I make a type out of any name? How do I know when I have to use the name of an object to create a type?

The script PlayerController is a class and can hold any data you add to that class. If you find the class PlayerController.cs and open it you’ll see all the properties that make up that class.

You can make a class of any name and it can have whatever properties or functions you wish to add to it.

Hi,

But what kind of data does a PlayerController type hold?

I would refer to that as PlayerController data. Your class for example may have multiple members, as @Stephen_Crookes suggests above, if you add a field for the player’s name, as a string then this would become one of the data items it contains. With a class named as PlayerController I would imagine this could cover a number of specific data items that relate to the player, or player interactions within your game.

What do you call types made from the names of other objects?

I’m not quite sure I understand this question. Creating a class defines a type. When you reference these classes with variables, your variables can be of any choice of name you like, but you should consider the relevance of the name.

Can I make a type out of any name?

Yes, you can create a class with a name of your choice, however, you should give some consideration to any clashes in the naming, for example, creating your own class called String may be a bad idea, as you may find clashes with the System.String. Although these classes would effectively be in different namespace, e.g. System and your class being in your project as a default namespace, it is generally best to name your classes based upon what they represent.

How do I know when I have to use the name of an object to create a type?

Again, I’m not entirely sure I’m clear on what you mean here, but I think you are talking about the differences I will try to outline in an example below;

public class LevelManager : MonoBehaviour
{
    public void LoadLevel(string name)
    {
        Application.LoadLevel(name);
    }
}

Ok, so in the above example, we have a class called LevelManager, it has a public method called LoadLevel, this method expects to be passed a string which will represent the name of the level we wish to load.

In order to use our LevelManager, we would either expose a public field and drag our LevelManager GameObject from the scene into this field, or perhaps find the LevelManager in the scene (you do this in BlockBreaker).

In our code, we would have something like this;

private LevelManager levelManager;

private void Start(
{
    levelManager = GameObject.FindObjectOfType<LevelManager>();
}

So, here, the lower-cased levelManager is our variable of type LevelManager (our class).

In order to use it’s LoadLevel method, we would have a statement perhaps like this;

levelManager.LoadLevel("MyFirstLevel");

Note, the lower-cased variable, and how we are passing in the name of our level as a string, as per the method’s definition in our class.

The above outlines an instantiation approach, e.g. we have an instance of our LevelManager class, in this case, attached to a GameObject in the scene, which we have either passed in by reference, or, found (as per the example above).

An alternative, would be to make our LoadLevel method static. This would allow us to call the method without first having to instantiate an instance of our class, and I think this may be what you are asking, with regards to the use of the class name (type) as opposed to the variable name.

If we re-write our LevelManager like this;

public class LevelManager : MonoBehaviour
{
    public static void LoadLevel(string name)
    {
        Application.LoadLevel(name);
    }
}

Note, the use of the static keyword in method definition now, we can call this method without having to instantiate our class, for example;

LevelManager.LoadLevel("MyFirstLevel");

Because we do not have an instance variable, we use the class name, hence the upper-cased LevelManager, followed by the name of our static method.

In fact, if you look at the Application.LoadLevel method which we subsequently call, this is doing exactly that.

I’m not 100% certain whether this was the question that you were asking here, but I have a feeling it was, if not, my apologies, but I would need a little more clarification, perhaps you could provide an example etc.

1 Like

It doesn’t answer my original question but it did help me understand a few things a little better.

First, I think I need to know some terms. In your example:

private LevelManager levelManager;

What do you call “levelManager” (lowercase)? Is it an Instance variable? Perhaps a Reference variable?

Is levelManager of type LevelManager the same as “dataHolder” of type firstEnum in this example:

private enum firstEnum {data};
private firstEnum dataHolder;

I think once I know what to call these variables I can pose a clearer question.

On a side note, is there a section in GameDev.TV where I can get help in Unity for my own game that isn’t related to a course? I’m making a runner game as practice but I’m stuck and not getting any help over on the Unity forums. Perhaps in the Lounge on here? Or would Discord be an option?

Thanks again for your continuing help!

1 Like

What do you call “levelManager” (lowercase)? Is it an Instance variable? Perhaps a Reference variable?

Correct, in this situation this would be referred to as an instance variable.

Variables which are declared within the body of a method are referred to as local variables.

A class can (and usually do) have attributes (consider player name in the PlayerController example), these attributes are referred to as fields, they are declared inside fo the class but outside of the method declarations within the class.

When each object of a class maintains its own copy of an attribute, the field that represents the attribute is referred to as an instance variables, each object (instance) of the class has a separate instance of the variable.

Is levelManager of type LevelManager the same as “dataHolder” of type firstEnum in this example:

Effectively yes, the type that has been created is firstEnum, so on the second line you are declaring a private variable of type firstEnum, dataHolder is then just the variable name (could be anything).

When you declare an enum you are declaring an enumeration, it’s a distinct type that consists of a set of constants, these are referred to as the enumerator list, in Text101 these were your varying states (cell, mirror_0 etc).

Each enum type also has an underlying type, the default is int, as such, each constant in the enumerator list will have a value, these start as 0 (zero) and increment, unless otherwise defined, for example;

private enum Days { Mon, Tue, Wed, Thu, Fri };

The days of the week in the above are the constants, the underlying type is int, because we haven’t specified otherwise, the constant’s values will be 0, 1, 2, 3, 4.

You can, of course, specify these values also;

private enum Days { Mon = 10, Tue = 20, Wed = 30, Thu = 40, Fri = 50 };

To give a little context to a benefit of being able to do this, these could be perhaps power-ups in a space shooter, perhaps each power provides a score multiplier, the values of each contant could be this multiplier.


On a side note, is there a section in GameDev.TV where I can get help in Unity for my own game that isn’t related to a course? I’m making a runner game as practice but I’m stuck and not getting any help over on the Unity forums. Perhaps in the Lounge on here? Or would Discord be an option?

I would suggest using the main category on the forum here, Unity, for example, e.g. not a specific sub-category which relate to the specific course(s) sections.

The Discord channel is also open to you, there are often many people there who will be able to help in realtime. The best approach may be to actually post the query in the Unity category here, you can then use the formatting and lay everything out easily, then, take the link to your post and post a query on Discord also, pasting in the URL. Other students will then be able to pop across to the forum and see everything in detail as they wish.

Be prepared to zip / share the project files also, as it is often a lot easier for those trying to help you if they can see things in context. Screenshots are useful of issues within the Unity Inspector or error messages, but for code examples I would consider copy/paste.

Hope this helps :slight_smile:

Thanks again for your continuing help!

You are very welcome :slight_smile:

1 Like

Okay, Instance variables. So what my original question was “what other times do I have to use Instance variables?” Though I think I know the answer now.

It’s anytime you need a variable to store an instance of an object/variable in order to access it’s data/fields.

So if I want to access the fields and methods in a class, or the constants in an enum.

What else do I need instance variables to manipulate? Arrays? Lists? Something not explained in the course yet?

This is what I’ve been trying to find out.

1 Like

What else do I need instance variables to manipulate? Arrays? Lists? Something not explained in the course yet?

The answer to that would be enormous, as there are so many classes/types within the C# library, but with both arrays and lists, you would indeed create a new instance of those.

The short answer would really be, to access any non-static classes/class members.

When it comes to determining how you use/access the various classes in both C# or Unity, I would suggest that in the first instance, take a look at the documentation, I don’t mean that as a flippant remark, but as you are clearly very interested in how things all work/fit together, you will find that both the Unity and Microsoft C# documentation is very good. For example, if were take a look at Unity’s Application.LoadLevel documentation;

https://docs.unity3d.com/ScriptReference/Application.LoadLevel.html

It states at the very top;

public static void LoadLevel(int index);
public static void LoadLevel(string name);

So immediately you can see that the method is a static method, this, along with the other information you now know, will help you to write your code - e.g. you know you don’t need a create a new instance of Application in order to use it.

(the same is true of it’s replacement in the newer versions of Unity, SceneManager).

When you look at some of the Microsoft documentation, don’t be put off by the voluminous nature of it, for example, this is the page for the List;

https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

Unless you are specifically looking for one of it’s properties/methods, I would start by taking a look at the description at the top, maybe the constructors (where appropriate) and then scroll down to the examples. From here you are likely to start using a List for example and may think, “hmm, I wonder how I get the total number of items in the list”, so, you could refer back to the properties/methods and see what is available, for example, the Count method.

My point here I suppose is to not be overwhelmed by documentation like this.

I hope the above is of use :slight_smile:


Updated Sun Dec 10 2017 10:17

Incidentally, by no means am I suggesting you only refer to the documentation and don’t ask for any help or support either via the Q&A on Udemy, here in the forum, or on the Discord channel. There will of course always be people here to offer help and support :slight_smile:

Alright, so it’s something I’m going to learn over time. I thought there might be a handful of times I would have to use instance variables.

Documentation has always deterred me since I can barely understand them most of the time.

One last thing. For the suggestion on where to post my non-lecture question, you mean to post inside the course but outside of a lecture sub-forum correct?

1 Like

Hi,

Alright, so it’s something I’m going to learn over time.

I think to some degree you will find that is the case. It’s likely to occur when you find yourself wanting to do something you’ve not done before, perhaps the first time you use an array / list for example. The first time you want to make a string all uppercase. Invariably you probably won’t be the first person to have wanted to do what you are trying to do, there will be some answers/info/guidance available online and in the process of looking at those the documentation is always there to help backup the examples/suggestions.

Documentation has always deterred me since I can barely understand them most of the time.

I understand how you feel and the Microsoft documentation is very verbose, which is great if you need it to be, but can be very daunting if you’re not initially sure what you’re looking for. The Unity documentation is reasonably user friendly I find. Again, you can always post and ask a question :slight_smile:

One last thing. For the suggestion on where to post my non-lecture question, you mean to post inside the course but outside of a lecture sub-forum correct?

Yes, so you might for example post under Unity, so that the query is still relevant to the subject, but perhaps not inside Text101 or Block Breaker sub-categories for example if the query doesn’t really relate to those.

Thanks again for sticking through this for so long, you’ve been a big help!

1 Like

You are very welcome :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms