Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

EdgeCollider2D IsTouchingLayers Issue

Discussion in 'Scripting' started by adsil_9000, Mar 16, 2021.

  1. adsil_9000

    adsil_9000

    Joined:
    Mar 12, 2021
    Posts:
    2
    Hi! I am new to unity and to this forum, but I have been having trouble with my code. I have a gameObject called spawnedObject and each layer is properly labelled "Foreground." I have my code here:
    Code (CSharp):
    1.  
    2. if (spawnedObject.GetComponent<EdgeCollider2D().IsTouchingLayers(LayerMask.GetMask("Foreground")) == true){
    3.             Debug.Log("is touching another foreground");
    4.             }
    5.  
    The debug.log never pops up, even if the gameObject is clearly touching a gameObject from that layer. Any help would be appreciated in figuring out why my code won't work.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    How did you get it there? If you drag it there or move it by .Translate() or setting .position, you are bypassing the physics engine.

    Always use the .MovePosition() / MoveRotation() method(s) on the Rigidbody / Rigidbody2D.
     
  3. adsil_9000

    adsil_9000

    Joined:
    Mar 12, 2021
    Posts:
    2
    Thank you for replying! I basically spawn my gameObject into my world and I want to ensure that it does not collide with another gameObject when spawning in.
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,546
    IsTouchingLayer checks for existing contacts, it doesn't perform a query of the world so if there's not been a simulation step then there won't be any contacts for a new collider so it'll not show as touching anything.

    If you want to do this before a simulation step then perform one of the many queries such as OverlapCollider.

    Please note that there's a dedicated Physics forum for this kind of stuff.
     
    adsil_9000 and Kurt-Dekker like this.