- Home /
How to find if my gameobject is the one being hit in a certain layer? (not through tags)
I am hitting my character with an enemy attack. the enemy attack has a script attached to it, which checks if it is hitting my character in the layer. I want to check if the the gameobject being hit is my character or not. Here is the code:
private Archer archer;
private LayerMask layerMask;
private void OnCollisionEnter2D(Collision2D collision)
{
layerMask = GetFinalLayerMask(8,12);
**if (layerMask.Equals(archer))
Debug.Log("Archer detected");**
Destroy(gameObject);
}
private int GetFinalLayerMask(int ArcherLayer, int CastleLayer)
{
int layer1 = 1 << ArcherLayer;
int layer2 = 1 << CastleLayer;
return layer1 | layer2;
}
I know that the code i have made bold is wrong but i don't know what to do. also i do not want to do this through tags because i think there might be a other way, and i'm using tags for something else.
Answer by Pangamini · Apr 30, 2020 at 04:19 PM
LayerMask is a bit flag integer. Means that each bit in 32bit number represents one layer. I will assume that archer is a Component. Then you can get its layer by accessing archer.gameObject.layer
. To find if this layer bit is set, bitshift using the layer, such as int archerMask = 1<< archer.gameObject.layer;
. Now, you still don't want to compare those, because archerLayer has exactly one bit set, while your layerMask has two (or any arbitrary number of bits, if it's any arbitrary bitMask. So in order to find out, if any bit from archerMask is set in layerMask, do a bitwise AND:
if ((layerMask & archerMask) != 0)
Your answer
Follow this Question
Related Questions
RayCast vision testing for same layer objects? 2 Answers
layermask does not exit in the context. What does this mean? 1 Answer
How can I have a raycast ignore a layer completely? 2 Answers
How can I prevent my EditorGUI.Maskfield from showing Mixed... ? 1 Answer
Physics2D.SetLayerCollisionMask delays before being applied 0 Answers