Using Layer Masks in Unity
Overview:
Let's look at how we can use layer mask in Unity.
Layer Mask:
A GameObject can use up to 32 LayerMasks supported by the Editor. The first 8 of these Layers
are specified by Unity. the following 24 are controllable by the user.
Setting Up Layer Mask:
I have 3 capsules in the scene 2 enemies and one teammate. let's create two new layer mask and assign the accordingly.
- With enemy one selected inside the top right corner in the inspector window click on layer mask then add layer.
2. layer 8 I named Enemy and layer 9 I named Friendly.
3. Assign the Enemy layer to both enemies and assign the Friendly to the Teammate.
4. Now let's write a script that will detect the layer mask using a Raycast and assign the script to the Main Camera.
public class LayerMask : MonoBehaviour
{
private Health _health;
[SerializeField] private bool _friendlyFire = false;
private bool _canAttack;
[SerializeField] private TextMeshProUGUI _friendlyFireValueText;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.T))
{
FriendlyFire();
}
if (Input.GetMouseButtonDown(0) && _canAttack || Input.GetMouseButtonDown(0) && _friendlyFire)
{
if (_health != null)
{
_health.Damage(10f);
}
}
}
void FixedUpdate()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, 1 << 8))
{
Debug.DrawRay(ray.origin, Camera.main.transform.forward * 1000, Color.green);
Debug.Log($"Hit: &{hitInfo.collider.name}");
if (hitInfo.collider.TryGetComponent<Health>(out Health health))
{
_health = health;
}
_canAttack = true;
}
else if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, 1 << 8 | 1 << 9) && _friendlyFire)
{
Debug.DrawRay(ray.origin, Camera.main.transform.forward * 1000, Color.green);
Debug.Log($"Hit: &{hitInfo.collider.name}");
_canAttack = true;
}
else
{
Debug.DrawRay(ray.origin, Camera.main.transform.forward * 1000, Color.red);
_canAttack = false;
}
}
public void FriendlyFire()
{
_friendlyFire = !_friendlyFire;
if (_friendlyFire)
{
_friendlyFireValueText.color = new Color32(27, 255, 0, 255);
_friendlyFireValueText.text = "ON";
}
else
{
_friendlyFireValueText.color = new Color32(255, 0, 0, 255);
_friendlyFireValueText.text = "OFF";
}
}
}
The Result:
The Enimies take damage but the friendly wont unless we turn on friendly fire.
Thats it for this article.
Thank you for your time and attention.