- Home /
Unable to set collision layer from scrip
Hi Guys.
I want to make a collision just against one kidn of object in my world, a "Tile". I have defined a Tile layer (9) but the following fails:
When creating the tiile:
GameObject newTile =
(GameObject)Instantiate(
trec.GetPrefab(),
new Vector3(rec.x*10,rec.e,rec.y*10),Quaternion.Euler(new Vector3(-90,((int)rec.facing)*90,0)));
newTile.transform.parent = rootObject.transform;
GameObjectUtils.SetShader(newTile,noCullShader);
tileGrid[rec.x,rec.y] = newTile;
newTile.layer=LayerMask.NameToLayer("Tile");
StaticBatchingUtility.Combine(new GameObject[]{newTile}, rootObject);
And when doing a collision test:
if (Physics.Raycast(ray,out hit, Mathf.Infinity,1<<LayerMask.NameToLayer("Tile"))){
tileMap.SetStartPoint(hit.point);
}
For grins I tried changing the first code to
newTile.layer=LayerMask.NameToLayer("Ignore Raycast");
And removed the layer mask from the raycast, and I got a hit.
It really looks like setting the layer in code just isnt working. Why not? is there some special magic about objects created by instantiating prefabs?
For the first part, do you mean it fails to set the layer (you check newTile and the layer is still 0)? NameToLayer
returns -1 if you spell it wrong, etc... -- maybe Debug.Log
for a test?
But, unless you're changing layers, why not just set the prefab tile to layer Tile?
I could, but there is a small question of correctness in that the tiles are comign from abundle that is made by a different project. So the loop is "open" in the sense that the "Tile" layer has to be set identicle in both projects. By setrting it in the instantiation project there is no way they can be diffrent.
Besides, it just annoys me that thius doesnt work. It seems like it should...
I think changing layers of Instantiated objects does work and something else in your code is the problem.
I know changing layers of pre-existing GO's through layer=new0-31LayerNum
works fine -- the very next frame raycasts react to the new layer. There could be some odd glitch specific to prefabs and layers, but I doubt it.
Unfortunately, I treid goign to set the layer on the prefab in the editor, but these are imported collada assets and the entire "Imported Object" section of its properties is greyed out and un settable :(
Well, you can turn a locked imported model into one of your own prefabs by dragging it into the scene, the dragging it back to an empty prefab.