Interesting observations on declaring a constant

I have observed some interesting behaviour when declaring gridSize in the Waypoint script as a const. I was wondering why the CubeEditor script did not simply call the variable gridSize in Waypoint script with the statement “gridSize = waypoint.gridSize”, as opposed to calling the method GetGridSize. So I tried it. In the Waypoint script, I edited the defining statement to “public const int gridSize = 10;”. I noticed however that gridSize was not showing up in the inspector, nor was “gridSize = waypoint.gridSize” in the CubeEditor script deemed acceptable. But if I removed the letters “const” from the declaration in Waypoint script, gridSize showed up in the inspector, and was acceptable to its use in the CubeEditor script.

So it seems that “public const int gridSize =10;” will compile without any errors, but the use of “const” nullifies the use of “public”, and requires the method GetGridSize() to access the constant. I found this interesting and thought I’d share.

Good reminder indeed. This StackOverflow question covers that pretty easy-to-understand manner

So consts simply are not accessible because they are not instance members (as far as I understand).
I think it would be possible to access that using class like this:

int gridSize = Waypoint.gridSize;

Difference in that is that I’m referring to Waypoint class, not waypoint instance of class. However I’ve pretty much never saw that in real life and I think it’s bad practice so I will stick with getter functions myself.

I was wondering why the CubeEditor script did not simply call the variable gridSize in Waypoint script with the statement “gridSize = waypoint.gridSize”, as opposed to calling the method GetGridSize.

Because const values are static, so you call the actual class definition Waypoint, not an instance waypoint.

So it seems that “public const int gridSize =10;” will compile without any errors, but the use of “const” nullifies the use of “public”, and requires the method GetGridSize() to access the constant. I found this interesting and thought I’d share.

Not really, no. If you use public const int gridSize =10; then you can reference it as a STATIC method (const implies static). So you can call it from any other class by int myGridSize = Waypoint.gridSize; . Note the class name Waypoint, not the instance name waypoint with lower-w. Without the public keyword, you could only use gridSize within other Waypoint instances.

Privacy & Terms