13. Classes and objects

Group a count with the operation that increases it. A class defines such values and operations. Classes other than Program unlock with your first Recompile.

A Counter that counts calls

ArcaneScript
public class Counter
{
    public int count = 0;

    public void AddOne()
    {
        count++;
    }
}

public class Program : ArcaneProgram
{
    public void OnStart()
    {
        Counter first = new Counter();
        Counter second = new Counter();
        first.AddOne();
        if (first.count == 1 && second.count == 0)
        {
            Workshop.Log.Write("Each instance has its own count.");
        }
    }
}

Counter defines a value named count and a method named AddOne. A variable declared inside a class but outside its methods is a field.

new Counter() creates one object that holds values according to this definition. An object created from a class is also called an instance. The example uses new twice, creating two separate instances.

Which value increases?

first.AddOne() calls AddOne on the Counter selected by first. The count inside that method belongs to that instance.

Point in executionfirst.countsecond.count
After creating both objects00
After first.AddOne()10

public lets Program use count and AddOne. private would restrict them to Counter. Here count is public so the example can inspect it.

Assignment does not create an object

Counter other = first; makes other and first select the same Counter. A value that identifies an object is a reference. Calling other.AddOne() also increases first.count. Use new as in the example when you want separate instances with separate values.

Arrays work this way too. Assigning an array to another variable does not copy its contents.

The Program class you have been using

Program is also a class. Program : ArcaneProgram makes it inherit from the game's ArcaneProgram class. This mechanism is called inheritance and gives Program access to Workshop. OnStart and OnTick are methods of Program.

Exercise

Add a second first.AddOne() call to the example. What are the two counts now? Update the if condition to check them.

Show example solutionHide example solution

first.count is 2 and second.count is 0. Change the condition to first.count == 2 && second.count == 0 to display the message. second is a separate Counter, so increasing first does not change it.