Variables in Script

Basics

After creating the script, it became your component. And in this component (further I will keep in mind about the linked script) you can create parameters and variables. Often all types of variables in C# can be used, as well as some non-standard types such as GameObject. All of them will be displayed in the inspector and in most cases they can be changed.

using Force;

public class Player : MonoScript {

	public string name;
	public int age;

	// Runs when scene starts to play.
	public void OnStart() {
		Debug.Log("Hello! Im " + name + ", and my age is " + age);
	}
}

This code creates an editable fields in the Inspector labelled “Name” and "Age".

Name and Age fields from script

In the inspector, you can edit variables. For a string, we enter the name Danil, and for a number, we enter 20 as the age. The names of variables to show in the inspector will format it a little, for example, making the first character uppercase or removing unnecessary characters like _.

Test the script

Note: In order for a variable to be visible in the inspector, it must be declared as public, as well as for C#.

Force will actually let you change the value of a script’s variables in runtime. This is very useful for changes directly without having to stop and restart. When gameplay ends, the values of the variables will be reset to whatever they were before you pressed Play.

Attributes

You can hide or show in inspector the field for special cases. For that you need to use attribute class on the field ShowInInspector.

using Force;

public class Player : MonoScript {
	[ShowInInspector()]
	string name;
	public int age;
}

In this case field name will be visible in Inspector even if it private or protected or have default access modifier. This very usefull when you need to have yours variable be hidden or private from others, but visible in Inspector.

Also you can disable field for editing in Inspector using another class attribute DisableInInspector.

using Force;

public class Player : MonoScript {
	public string name;
	[DisableInInspector()]
	public int age;
}

In second example field age will be only read only and not editable from Inspector.

Properties

C# has another type of variables to declare along with fields is properties. Generally speaking im firstly discover its existence only now when starting to improving Force scripting engine.

So Force itself starting to support them, you can declare it in the script, but only illumination for now that they will not display in Inspector. So you need declare normal field first and then use it in property for getter or setter.

using Force;

public class Player : MonoScript {
	
	public string propertyField;
	public string Property { get { return propertyField; } set { propertyField = value; } }
}

Last updated