Layer Setup using Serialized fields

The following allows us to define layers via Unity vs. hardcoding them.

I created a PlayerCollision script to avoid cluttering up the PlayerMovement script. Attached it to the prefab.

Note the GetCollisions and IsTouchingLayers functions I made. This was to make use of list and arrays to detect layer collisions reusable. So, you could add additional layers like slowLayers, and then add something like if (isTouchingLayers(slowLayers).

Below you can see everything and how I set it up:


And, then in your PlayerCollection script:

    [SerializeField] Vector2 deathKick = new Vector2(0, 20f);
    [SerializeField] List<string> deathLayers = new List<string>();

    PlayerMovementScript playerMovement;
    CapsuleCollider2D myBodyCollider;
    Animator myAnimator;
    Rigidbody2D myRigidBody;

    bool isDead = false;

    private void Start()
        playerMovement = GetComponent<PlayerMovementScript>();
        myBodyCollider = GetComponent<CapsuleCollider2D>();
        myAnimator = GetComponent<Animator>();
        myRigidBody = GetComponent<Rigidbody2D>();

    private void Update()
        if (isDead) { return; }


    void GetCollisions()
        if (IsTouchingLayers(deathLayers))

    bool IsTouchingLayers(List<string> layerList)
        string[] layers = layerList.ToArray();
        int layerMask = LayerMask.GetMask(layers);

        return myBodyCollider.IsTouchingLayers(layerMask);

    void Die()
        playerMovement.isEnabled = false;
        myRigidBody.velocity = deathKick;      
        isDead = true;

You can define the type and then pick the layers in the inspector the way all the built-in components do

[SerializeField] LayerMask deathLayers;


1 Like

Privacy & Terms