informa
/
1 MIN READ
Blogs

Particular Problems with Public Variables in Unity

In the Unity documentation it is indicated that all public variables are made available in the inspector for direct editing. While this is handy, it is also dangerous.

 

The Unity documentation it indicates that all public variables are made available in the inspector for direct editing. While this is handy, it is also dangerous. This article will cover a few things regarding public variables, and how to avoid them in Unity.

Public Variables

In a earlier post I made mention of public variables, specifically in a class-based architecture. One of the dangers of public variables is that anything can change their value. When testing Napkin Western (working title) on a tablet, some of the variables were corrupted from the values set in the Inspector. The values changed from 6 and 15 to 2.435e-43 and 2.643e-45 respectively.

Solution

What's the solution? Simple, set the access to all your variables, functions, enums, etc. to exactly what they should be. Make only variables public that absolutely need to be. Then take advantage of the [HideInInspector] to keep certain public variables hidden, and [SerializeField] to show hidden or private variables. This way things won't get accidentally modified, and you will have access to all the pieces you need while retaining the proper level of access.

 

Latest Jobs

IO Interactive

Hybrid (Malmö, Sweden)
3.02.23
Gameplay Director (Project Fantasy)

Arizona State University

Los Angeles, CA, USA
2.27.23
Assistant Professor of XR Technologies

IO Interactive

Hybrid (Copenhagen, Denmark)
3.02.23
Animation Tech Programmer

Purdue University

West Lafayette, IN, USA
3.02.23
Assistant Professor in Game Design and Development
More Jobs   

CONNECT WITH US

Explore the
Advertise with
Follow us

Game Developer Job Board

Game Developer

@gamedevdotcom

Explore the

Game Developer Job Board

Browse open positions across the game industry or recruit new talent for your studio

Browse
Advertise with

Game Developer

Engage game professionals and drive sales using an array of Game Developer media solutions to meet your objectives.

Learn More
Follow us

@gamedevdotcom

Follow us @gamedevdotcom to stay up-to-date with the latest news & insider information about events & more