StyleCop to check c# coding style in Unity, is it possible?

Hi, I am working on a game project in Unity 3.5.

All the C# script files are written in Visual studio 10 with StypleCop already installed. Stylecop is a VS10 add-on that let user define a set of rules to check for coding styles (space, name, layout, etc.)

The actual build/test will be done in Unity, any chance that I can do a StyleCop automatical check in Unity pre-build?

Thanks a lot.

There is one StyleCop rule that you will want to override in all MonoBehaviour scripts:

SA1401: FieldsMustBePrivate

"A field within a C# class has an access modifier other than private.

Rule Description
A violation of this rule occurs whenever a field in a class is given non-private access. For maintainability reasons, properties should always be used as the mechanism for exposing fields outside of a class, and fields should always be declared with private access. This allows the internal implementation of the property to change over time without changing the interface of the class.
"

Unity 3.x Inspectors can’t show Properties, only public Fields. (I’m not sure if this has been remedied in 4.x) So if your MonoBehaviour has any public fields for the user to set in the Inspector (which is nearly all of them) you will either need to create a custom inspector (tedious) or (simpler) suppress the violation by adding the following attribute:

I’d actually leave StyleCop to flag these.

You can use

[SerializeField]
private int example;

To serialise the field, and make it appear in the inspector. Making a variable public does exactly the same thing, but just exposes it to all other classes. Plus, using [SerializeField] it’s is a nice habit to pick up, since you’ll be getting better encapsulation.

1 Like