Enforcing components

Since we need to use this script along with the collider and the RigidBody we have attached before on our player, we need to enforce this by saying that every time we use this script, the object on which this script is attached must have a collider and a RigidBody. As a result, we won't wrongly use this script without those components.

We can achieve this by adding two lines of code above the class definition, as highlighted here:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(CircleCollider2D))]
public class PlayerController : MonoBehaviour {
//[…]
}
If you want to do a more general script, you can have Collider2D instead of CircleCollider2D. As a result, you will be able to use any collider, but then you need to remember which one is the right collider for the character you want to use.
..................Content has been hidden....................

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