I just can’t seem to get this to work, no matter how many things I read. I have cobbled together the following code from a few sources:
function UpdateUnitsPresent(currentPlayerTurn: int){
var currentPlayerLayerMask: LayerMask = 1 << LayerMask.NameToLayer("player1Unit"); //Once I have this working I will change player1Unit to a containt the currentPlayerTurn
print(LayerMask.LayerToName(currentPlayerLayerMask));
var colliders : Collider[] = Physics.OverlapSphere (this.transform.position, 0.004, currentPlayerLayerMask);
for (var hit : Collider in colliders) {
if (!hit){
continue;
}
if (hit.rigidbody){
print("hit: " + hit.gameObject.name);
}
}
}
I have edited this in many ways in order to try to get it to work, but to no avail. The objects with colliders that have the"player1Unit" layerMask have it set through a static variable in their respective scripts (see below). I know that the issue is either in the code above, or below, since the OverlapSphere code works correctly if I manually change the main layer in the dropdown list at the top of the inspector, but doesn’t work if I manually set the LayerMask assigned via a variable in the inspector. I have tried hard coding it (var currentPlayerLayerMask: LayerMask = 1 <<x) but I end up getting layer 2^x being selected from that…I’m obviously missing some important information regarding how this works.
Assigning LayerMask on the objects themselves:
static var thisUnitsLayer : LayerMask;
function Start(){
thisUnitsLayer = 1 << LayerMask.NameToLayer("player1Unit");
print(thisUnitsLayer.value);
}
The value that prints is 2048, which should be layer 11 (which is the correct in the inspector) if I have understood some of the sources I have read.
Thanks, but I’m still not sure how exactly I’ve gone wrong. The Physics.OverlapSphere asks for a LayerMask, and I had been trying to assign a LayerMask via the code (rather than Layer, assuming there is a difference?). It seems odd that the Overlap sphere is detecting the layer assigned in the inspector (and presumably if assigned with the method that you state), but not with a LayerMask assigned through the code. I only changed the Layer in the inspector as part of the debugging process to see if had any impact on what was going on.
Ideally I would like to use LayerMasks, rather than the main Layer in the inspector, since I think I could then focus in on very specific types of units owned by particular players (i.e. unit is assigned multiple LayerMasks).
Just in case, I’m not sure you are using ‘layers’ as intended
A game object can only be on a single layer, and when you do the physics cast, the layermask is used to ignore/exclude/include objects on certain layers
the mask (1<<8) will only return hits against object in layer 8
Thanks, yeah it would be straight foward enough to write my own labels, I would have just made use of an inbuilt multi-tag/labeling system if there was one!