Categories
Coding Tips Game Development Unity Tips

Quick Unity C# Tip | Properties

So, when it comes to using properties in Unity one of the most annoying things to do is debugging, by default there is no way to see properties in the inspector, but you can assign a variable to be a kind of pass-through for the property value which you can see in the inspector. This is the topic of this quick post, which is how you do this.

Now properties will either a get, set or both. below is an example of a property with has a default get and set;

private int IntProperty { get; set; }

This allows you to get the value and use it in your code perfectly fine and for most part is what you’ll use when using defining properties, including in interfaces, which you can see my post about here if you’ve never heard of them before. However, the default definition doesn’t let you see the value without the use of a debug.log or some UI/GUI. So instead we add a variable and make it be get and set by the property, like so;

private int intVariable;

// One line
public int IntProperty { get { return intVariable; } set { intVariable = value; } }

// Spaced Out
public int IntProperty
{ 
	get 
	{ 
		return intVariable; 
	} 
	set 
	{ 
		intVariable = value; 
	}
}

This essentially means you can edit the local variable or the property and it will edit the value. Though the property is the only editing part outside of the script. However it can be written in a neater fashion, like so which is also the auto fill if you using the Rider IDE. This is also the way I now write properties if need to see them in the inspector;

private int intVariable;

// One line
public int IntProperty { get => intVariable; set => intVariable = value; }

// Spaced Out
public int IntProperty
{ 
	get => intVariable; 
	set => intVariable = value; 
}

As always, you can just have a getter or setter which can be written on just one line for neatness.

private int intVariable;

// one line getter
public int IntProperty => intVariable;

// one line setter
public int IntProperty => intVariable = value;

And that’s it, hopefully this tip was useful to y’all, even if it was just the neater syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *