Search Unity

Changing to a different layer via script on Raycast hit

Discussion in 'Scripting' started by Eversmann, Mar 15, 2019.

  1. Eversmann

    Eversmann

    Joined:
    May 3, 2013
    Posts:
    29
    Is it possible to change layer via script? My click to move system uses Ground layer to determine where you can move, so that your character doesn't move somewhere you shouldn't like a wall or roof or so.

    I have a script that uses raycast from camera to detect if there is any object between player and the camera and fades it out (so like when you enter a house it fades out the roof). But what if you walk under a bridge that's tagged as Ground (so you can walk). Then clicking where the bridge was faded out would make you go up to the bridge.

    Any way that if raycast hit detects Ground layer on an object it's suppose to fade out, it changes it's layer to say Default or Transparency (so if you click where the object was you'll still move under it, and not go up to it) while it's faded out and then once it's faded back in, it changes back to Ground?
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Changing the layer a gameobject it on is a simple as
    Code (CSharp):
    1. gameObject.Layer = // Int value of the layer or a variable you declare somewhere
    What I would probably do though is have colliders either side of the bridge or some method to detect if the player is walking towards the side of the bridge where they would walk under and then just fade the bridge and disable it's main collider until they walk out again.
     
  3. Eversmann

    Eversmann

    Joined:
    May 3, 2013
    Posts:
    29
    Ah I haven't thought of that. So basically put a box collider under the bridge then add a simple script to disable the bridge's collider OnTriggerEnter and then enable it back OnTriggerExit? That could work I'll try that first. And thanks for the layer method too, I'll try that too if this doesn't work.
     
  4. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Yes, have a collider which disables your main bridge collider when the player enters it. That way, you can also fade out the bridge slight before the player gets under it as well rather than waiting for the raycast to discover the view of the play it obstructed. It may make navigation slightly easier in the game.
     
  5. Eversmann

    Eversmann

    Joined:
    May 3, 2013
    Posts:
    29
    Thanks. I've experimented with that but then I realized if the enemies/NPCs are on the bridge and you're under they'd just fall with no collider. So I implemented a simple script that changes the layer from Ground to Default upon OnTriggerEnter. Works good for now!