Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to check versus Interface or Class with Terrain collisions?

Discussion in 'Scripting' started by Inxentas, Jan 19, 2020.

  1. Inxentas

    Inxentas

    Joined:
    Jan 15, 2020
    Posts:
    277
    I have a piece of code in my game I already hate. The intention is to simply check whether a collision hits a terrain object, in case I want the collision to be handled in a specific way. I looked for a way to detect the terrain and went with this for now:

    Code (CSharp):
    1. if (collision.gameObject.name == "Terrain")
    2.         {
    3.             movement.grounded = true;
    4.             movement.jumpTimes = 0;
    5.         }
    Terrible! I've tried casting collision.gameObject to the Terrain class to get a satisfying bool, but that doesn't work. Basicly my goal is to isolate the Terrain class and check for that instead of some arbitary instance name. I'm new to the codebase so I figured the answer is probably quite simple and I'm just not seeing it yet :p
     
  2. Inxentas

    Inxentas

    Joined:
    Jan 15, 2020
    Posts:
    277
    ....aaaand I figured out a solution 5 minutes after posting. For anyone interested, my fix was to check for the TerrainCollider component (and I am still open for better ideas)!

    Code (CSharp):
    1. if (collision.gameObject.GetComponent<TerrainCollider>() != null)
    2.         {
    3.             movement.grounded = true;
    4.             movement.jumpTimes = 0;
    5.         }
     
  3. BackgroundMover

    BackgroundMover

    Joined:
    May 9, 2015
    Posts:
    215
    An alternative might be something like
    Code (CSharp):
    1.             if(collision.gameObject.layer == LayerMask.GetMask("Terrain")) {
    2.  
    3.             }