Is it possible to access Layer visibility and lock status via script?
I'm making a level editor and when an option is on in my EditorWindow script, I can select multiple gameobjects and add them to a collection.
I want to be able to select just the gameobjects in a particular layer, so when this option is on the other layers should be locked, but I'm unable to find any way to access layer properties from code.
Is it possible to do change layer's lock and visibility from my script? Is there some clever way to do that?
Thanks!
@mikilo the layer property to lock it and prevent the objects in it from being selected.
Answer by Mikilo · Sep 01, 2015 at 02:13 PM
Hahahaha!
I had an issue where I was unable to select objects in scene... You just gave me the explanation... XD
Anyway, you can toggle layer's lock state by calling :
InternalEditorUtility.SetSortingLayerLocked(index, state);
Since it is hidden, you need to call it through reflection. Will you need help?
Edit: With some further research, you might change it through Tools.visibleLayers and Tools.lockedLayers.
Hey @$$anonymous$$ikilo, thanks for your help! I got this to work, but I'm not sure it's the best way yet. I was able to call the SetSortingLayerLocked() function through reflection (and btw I had never used reflecion before, but encountered no difficulties in the process) but I supose this function is intended to work just with sorting layers and not with layer masks, which is my case. I ended up using the Tools.lockedLayers even though it has an odd behavior. It gets and sets an int number based on 2 to the power of the layer's index on the layers array. So the code turned out quite simple:
Tools.lockedLayers = (int)$$anonymous$$athf.Pow(2, Layer$$anonymous$$ask.NameToLayer("LayerName"));
I have no idea why that work this way, do you have any clue? And thanks again for your help!
P.S. Glad to know that I accidentally gave you an explanation about that issue. Haha!
Hi!
Oh no! Tools.lockedLayers is a mask (32 bits in 4 bytes in an integer).
Why is that? Because layers in Unity are used as a mask.
Also, about your code. Since you dont really know mask, I give you a tip about how to play with them.
Tools.lockedLayers = 1 << Layer$$anonymous$$ask.NameToLayer("LayerName"); // Replace the whole value of lockedLayers. Tools.lockedLayers |= 1 << Layer$$anonymous$$ask.NameToLayer("LayerName"); // Add a value to lockedLayers. Tools.lockedLayers &= ~(1 << Layer$$anonymous$$ask.NameToLayer("LayerName")); // Remove a value from lockedLayers. Tools.lockedLayers ^= 1 << Layer$$anonymous$$ask.NameToLayer("LayerName")); // Toggle a value in lockedLayers.
End of the story.