Let's go over first what actually happens with your code, so we can get an idea of how it works.
We'll use this code to make an instance of the class:
var vehicle = new Vehicle();
// set the items inside
vehicle.numWheels = 4;
vehicle.numAxles = 2;
Well, what does this do?
When code execution runs, it starts by running your constructor, and all the code inside it, before running the last two lines to modify the properties1. Your object must be fully instantiated before you can modify it.
Problem is, you'll never be able to fully instantiate the object.
Your class has two variables which you read from in the constructor, numWheels
and numAxles
. Both of these are (32 bit) integeters, and are uninstantiated - meaning you never directly assign them a value before you read from them.
However, int
types are Value Types in c#, which means they are never uninstantiated. If you don't set a value when you create the variable it will take the default value for that type, which in this case is 0
.
And then you try to do 0/0
, and an exception will be thrown.
The issue here is that you need to provide a value for your variables during creation of the class, as doing so afterwards is too late. The good news is that you can pass in values as arguments to the class's constructor.
public class Vehicle
{
public int wheelsPerAxle;
public Vehicle(int numWheels, int numAxels)
{
wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
}
}
var vehicle = new Vehicle(4, 2);
// "vehicle.wheelsPerAxel" is 2
Note: this doesn't do any validation, and it doesn't save (scope-wise) the values for use outside of the constructor, but this should get the point across.
See Pac0's answer for a more robust solution to modifying your class.
1 These are not properties, they are fields.