I cant get a gameObject´s layer (HELP)

Hey, I´m having isuues with this piece of code. I keep getting this error:

  • error CS0029: Cannot implicitly convert type ‘string’ to ‘int’
    It says it´s on the 3rd line. Can you help me please?

`void OnCollisionEnter(Collision coll)
    {
        if(coll.gameObject.layer = "Floor")
        {
            player.GetComponent<PlayerMovement>().isGrounded = true;
        }
        else
        {
            player.GetComponent<PlayerMovement>().isGrounded = false;
        }
    }`

Layers are integers, not strings.

Please refer to the LayerMask class documentation for methods to extract a layer from a given string, such as “Floor” .

Also, just so you know, code like this:

… is asking for trouble. It might work but when it fails it will be baffling and require refactoring.

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

Putting lots of code on one line DOES NOT make it any faster. That’s not how compiled code works.

The longer your lines of code are, the harder they will be for you to understand them.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

As Kurt mentioned, check out the LayerToName and NameToLayer functions in LayerMask if you like to work with strings for your layers.

But also, be careful with the comparison in your if condition. You have a single equal sign =, which is used for assignment. You need to use a double equal sign for comparison ==.

Here’s a link to the LayerMask documentation.

1 Like