Static code analysis is a standard practice in software development. There are code scanner tools, which scans the code to find vulnerabilities. There are some nice tools for visualizing and managing code quality. One of the most used tool is SonarQube, supports 25+ languages and flexible configurations of the rules.
There are not enough resources talking about static code analysis for Unity3D. This post covers steps to configure SonarQube and use it for scanning Unity projects.
SonarQube Server Setup
SonarQube requires a server setup where it manages code quality analysis, configuring rules and extensions. Follow the below steps to install and configure Sonar for local use. Make sure you have Java 8+ installed on your PC.
- Download SonarQube — https://www.sonarqube.org/downloads/ - Download Community Edition
- Unpack the zip sonarqube-8.0.zip as Directory
- OS-specific installations are available in the bin directory
- For Unix based OS provide permissions execute permission on
chmod +x SONAR_INSTALLATION/sonarqube/bin/<os-specific-folder>
- Start the Sonar Server —
Sonar Server is ready to be used at
http://localhost:9000 with credentials
- Set up your first project on Sonar Qube. — Click create
+on top right
It will ask you for the token which may be used to securely run the analysis on the sonar server. For now, leave it at this step, we will use user credentials admin/admin for simplicity. This project is created with default rules sets and quality gates. Remember the project key.
Sonar Scanner Setup
Sonar scanner needed to statically analyze the code against the rules on the sonar server and then push the reports to the sonar server. Follow the steps below to set up Sonar Scanner Ref : https://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-msbuild/
Analyze Unity Project
Create a Unity Project. Below is a simple Unity project with button which toggles its color on every click. Let’s statically analyze this project.
Follow the below steps :
Goto project root —
Start Pre-Processing for with Sonar Scanner — on windows we can directly run
SonarScanner.MSBuild.exe begin /k:"project-key" comes with Sonar Scanner, but on Mac we need run it with mono as follows.
mono /Applications/sonarscannermsbuild/SonarScanner.MSBuild.exe begin /k:”UnityFirst” /d:sonar.host.url=”http://localhost:9000"
Rebuild Project —
MSBuild.exe <path to solution.sln> /t:Rebuild
On mac :
Post-processing — push report to Sonar Server
Analyze code on Sonar Server — http://localhost:9000/dashboard?id=UnityFirst
Analyse the issues
In this post, we have learned setting up Sonar Server and Sonar Scanner and using it for Unity Projects. Also, see its usage on Mac.
The next post talks about setting it up for IDE and perform inline code analysis
This article was originally published on XR Practices Publication
＃static code analysis