How do you Set and Get variable and their values of any Game Object?

I’ve been trying to find examples of this and i find nothing.

I"m a beginner so i don’t even know how to use those and most examples out there just have difficult code.

Anyway

Say i have a C# Class for some enemy and in it it has a enemyEnergy variable.

Then
I have another C# Class for the player…and it wants to check the enemyEnergy and even modify it.

Would something like this work? i dont’ know the exact unity and c# code but i’ll just make something like i’ve used in other languages.

i would do this inside one of the Player script
→ if enemy.getEnergy( ) > 10 Then enemy.setEnergy( enemy.getEnergy( ) - 1) )

i kinda did it how it’s done in Java.

is that how it works???

So in unity what are the mehtods for this

how do you do this in Unity?


http://docs-jp.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

–Eric

Don’t stress over it since it’s not a big deal, but it’s a good idea to use C#'s best practices for this kind of thing. Instead of using getter/setter methods, C# provides access via “properties”. These look like variables, but accessing or changing them is actually a function call.

Using a property looks something like this:

private int IntValue
public int IntValue {
    get {
        return intValue;
    }
    set {
        intValue = value;
    }
}

In the example, “get” and “set” are keywords used to define the getter and setter parts of the property, respectively. If you don’t want a setter you can leave it out, or you can also make it as private (really handy - you can use this so that you’ve got a variable which is publicly accessible but can only be set internally, making for clean interfaces but elegantly minimalist code). Also, “value” is used to access the input value in a setter. Finally, you can of course do more than return or assign - for instance, in a setter it’s a good idea to sanity-check the value if relevant - but since other coders are expected to treat properties the same as they would a variable it’s best practice to put only trivial code in there.

One last note is that the example above shows what I think is considered best practice for naming style. Variables are named starting with lower case letters. If a variable is accessed via a property, then that property has exactly the same name but starting with a capital letter.