Exposing variables in the inspector

When in Unity, we attach components to our GameObject, there are some parameters (or variables) that designers can adjust. We would like to adjust the speed of our character from the Inspector. In this case, we will use a float, so decimal values can also be used.
The easiest way to expose a variable in the Inspector (there are other ways, but for now we won't see them) is to declare a variable public. Optionally, you can assign a value, which will be the default one in the Inspector. So just inside the class, we can add the following highlighted line:

//[…]
public class PlayerController : MonoBehaviour {

public float speed = 10.0f;

//[…]
}

As a result, if we go back in Unity, and see our character, we will see that now the speed is exposed in the Inspector, as shown here:

We get a reference to the Rigidbody, so we can use it to move the character. Sometimes during the execution of the script, we need to reference some other components that are attached to the object. The Start() function is a perfect place for this purpose. In fact, now, we need to retrieve the Rigidbody component. To do so, let's declare a variable, this time private since we don't need to expose it to the Inspector, as shown here:

//[…]
public class PlayerController : MonoBehaviour {

public float speed = 10.0f;

private Rigidbody2D rigidBody;

//[…]
}

Next, we need to assign the rigidbody of the character within the variable. So, inside the Start() function we can use the GetComponent() function to retrieve the RigidBody2D instance that is attached to the same game object this script is attached to, in the following way:

void Start() {
rigidBody = GetComponent<Rigidbody2D>();
}

Please note that we don't do any check of the validity of Rigidbody (if it exists), because at the beginning of the script we have enforced that Rigidbody must exist to use this script. As a result, we can avoid checking the validity of the variable (null-check), since we know Rigidbody will always exist.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset