Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

OnTriggerEnter2D with if/else

Discussion in '2D' started by BlinMaster1000, Sep 14, 2022.

  1. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    hello,
    i am currently working on my 1st game on Unity and I would like to add a gameObject that appears when the player collides with it and disappears when the player moves too far from it. Right now it can appear exactly how i wanted it to work but it won't disappear when the player goes away. Could someone please help me?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnableDisable : MonoBehaviour
    6. {
    7.     // Start is called before the first frame update
    8.     void Start()
    9.     {
    10.        
    11.     }
    12.  
    13.     // Update is called once per frame
    14.     void Update()
    15.     {
    16.         //for testing
    17.         if (Input.GetKeyDown(KeyCode.X)) {
    18.         GetComponent<Renderer>().enabled = false;
    19.         }
    20.     }
    21.    
    22.     void OnTriggerEnter2D(Collider2D col)
    23.     {
    24.         if (col.gameObject)
    25.     {
    26.         GetComponent<Renderer>().enabled = true;
    27.     }
    28.         else
    29.     {
    30.         GetComponent<Renderer>().enabled = false;
    31.     }
    32. }
    33. }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    Code (CSharp):
    1. if (col.gameObject)
    Can you explain what this is supposed to be doing? It'll always have a valid GameObject so this will always be true and always result in you enabling the renderer.

    You need to explain and maybe show what colliders are where and where this script is. Too many posts show a bit of script and a rough description. The main thing is provide the context.

    Use OnTriggerEnter2D for when you enter a trigger and OnTriggerExit2D for when you exit a trigger. If you don't know this then I would highly suggest following a basic 2D physics tutorial before you try to use it otherwise you're going to be guessing each step.

    This just looks like a continuation of this thread TBH: https://forum.unity.com/threads/how-do-i-make-a-key-appear.1335305/#post-8438879

    Also, please don't add random tags to posts. This is not related to 9-slice, performance, spriute-mask, tilemap etc.

    Thanks.
     
    NeilB133 likes this.
  3. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    hello, thanks for ur reply, and yeah i've tried to use OnTriggerExit2D but that didnt work, but tbh idk what col.gameObject means, i just tried something, could u explain to me what i should put there instead? thank you:)
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    I have no idea what "that didn't work means". That call works, how you're using didn't.

    If you don't know what it means then as I have said, you need to follow some tutorials. Forums are not tutorials. You can look this up with the scripting reference: https://docs.unity3d.com/ScriptReference/Collision2D.html

    I can appreciate you're a beginner but a forum cannot take you step by step through something like this. That's what tutorials are for. As you must understand and as I asked above (but you didn't respond to); I have no idea what scripts are where or what colliders are where. There is no answer to "what i should put there instead".

    I know this isn't what you want to hear but unless someone else wants to go through this step by step, I would encourage you to follow some tutorials to first understand how stuff works before you try using it.
     
  5. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    i've seen that happen in alot of other fora (also unity) so ur straight cappin'
     
  6. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    What?
     
  7. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    i've seen people get helped step by step on unity formum is what i meant by my last msg
     
  8. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    Yes, to specific questions. The next step I proposed for you is to follow some tutorials. You're quick at replying to what you want but you've still not provided any details that I asked for twice above.

    I originally asked this:
     
  9. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    o sorry :(, i will provide details here:)

    in green at 1 is my character which is the player
    at 2 is the object (a sign with the letter E) that appears when you get close (its invisible right now)
    also the script i showed u earlier is placed on the E sign, not on the player
    the player and the sign both have a 2D collider and the E has "istrigger" checked on

    if u need more details just tell me which and i'll tell u :) (except for creditcard details LOL)
     

    Attached Files:

  10. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    So I presume 2 has a trigger collider that extends the distance where you want the "E" to appear/disappear? Presumably a CircleCollider2D as a trigger? It's not shown in the image.

    You only mention that both have a 2D collider but if the player is moving, it must have a Rigidbody2D. A Collider2D that isn't attached to a Rigibody2D is Static (non-moving). Static colliders don't come into contact with static colliders because why would they; they don't ever move.

    You've only said OnTriggerExit2D didn't work. You didn't say whether OnTriggerEnter2D is working. Did you put in a "Debug.Log("Triggered!!!!")" into OnTriggerEnter2D to check if it is being called? If you've not added a Rigidbody2D to the player then it won't.

    If this is top-down then the Player Rigidbody2D should be set to a BodyType of Kinematic and you should use Rigidbody2D.MovePosition or Rigidbody2D.velocity to move it.

    Again though, this is all basic tutorial level stuff.
     
  11. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    yes the player has a rigidbody2D and as i said, the E does appear when the player gets close (exactly as intended). it just doesnt wanna disappear when the player moves away from it
     
  12. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    Where did you say that?

    You've already established that so why repeat it? I took the effort to type-out a bunch of stuff above but you've replied by restating this only. That doesn't help anyone. :(
     
  13. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    the "as i said" was meant for the sentence next to it not for the Rigidbody part :(
    also the reason i restated that about the E appearing is because after i read your message i thought u might've missed me saying it the 1st time:(
     
  14. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    I've given you a lot of information above, these replies don't help at all. I would suggest you read them and see how you get on.
     
  15. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    i will read them thanks for trying to help me and i'm sorry for my noobness
     
  16. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    It's okay and I'm happy to help. I would suggest though that when you only reply to things that don't really matter and not to the answers you've been given, it *seems* like you're ignoring the important bits and focusing on the stuff that doesn't matter. It's a perception thing only.

    I will say though. Create an empty project. Test this enter/exit trigger collider thing until you understand it. When you do, come back to your project and implement it with your new found knowledge. :)

    Good luck.
     
  17. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    i just read the entire pack of text u sent a couple minutes earlier and i'm not using the circle colider but a box colider, nothing is static and i made it dynamic because with kinematic the invisible walls dont work (idk how important this information is but here is it anyways) and thanks for wishign me luck :)
     
  18. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    So maybe show the trigger collider you're using so we can see how big it is.

    If the above script is on that object 2 then you will get a OnTriggerEnter2D and OnTriggerExit2D. Did you try adding a Debug.Log("Triggered!!") ? That will show you if those callbacks are happening.

    Like this:
    Code (CSharp):
    1.     using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.  
    5.     public class EnableDisable : MonoBehaviour
    6.     {
    7.         private Renderer renderer;
    8.  
    9.         // Start is called before the first frame update
    10.         void Start()
    11.         {
    12.             renderer = GetComponent<Renderer>();
    13.         }
    14.  
    15.         // Update is called once per frame
    16.         void Update()
    17.         {
    18.             //for testing
    19.             if (Input.GetKeyDown(KeyCode.X))
    20.             {
    21.                 renderer.enabled = false;
    22.             }
    23.         }
    24.    
    25.         void OnTriggerEnter2D(Collider2D col)
    26.         {
    27.             Debug.Log("OnTriggerEnter2D called!")
    28.             renderer.enabled = true;
    29.         }
    30.  
    31.         void OnTriggerExit2D(Collider2D col)
    32.         {
    33.             Debug.Log("OnTriggerExit2D called!")
    34.             renderer.enabled = false;
    35.         }
    36.     }
    37.  
    This will turn it on off for anything touching it so you need to use the Layer Collision Matrix to ensure only the player can interact with it.
     
  19. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    214
    I might be mistaken, (apologise if so!) but from looking over this thread it seems you might be guessing how things work, instead of taking the time to understand how they work. I know it can sometimes be a drag to go away and sit and watch tutorials, but it does pay off!

    Here's a few great ones to start with that are relevant to your issues:

    One in regards to Colliders and Triggers:


    One in regards to the differences between RigidBody Types:


    One in regards to Unity's Layer system and using the collision Matrix:
     
    Kurt-Dekker and MelvMay like this.
  20. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    YOOO thank u so much for fixing it up i will try to understand what u changed, (idk what the debug should do but the code works exactly like i wanted in the 1st place now thank you :):):):):):):):)
     
    MelvMay likes this.
  21. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    Note what I said though, the above script will get those callbacks when anything enters/exits the trigger. Be sure to use the Layer Collision Matrix so that only the Player "layer" can touch the layer the trigger is on.
     
  22. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    ok thank u i will look into that (idk what it means exactly yet)
     
  23. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,589
    Watch the video above, "The Unity Layer System" then. :)
     
  24. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    thank you, i will look into that :). but now im trying to make it so that when the player collides with the "E-sign", and presses E while being there, the next scene starts. i tried various things but i dont think i got the "next scene" part right.:confused:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class ToScene2 : MonoBehaviour
    7. {
    8.     private Renderer renderer;
    9.     private bool enterAllowed;
    10.     private string sceneToLoad;
    11. //    public static void LoadScene(string youcancallmesus, SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.          renderer = GetComponent<Renderer>();
    16. //         SceneManager.LoadScene("youcancallmesus", LoadSceneMode.Additive);
    17.     }
    18.  
    19.     // Update is called once per frame
    20.     void Update()
    21.     {
    22.        
    23.     }
    24.    
    25.      void OnTriggerEnter2D(Collider2D col)
    26.         {
    27.             if ((renderer.enabled = true) && Input.GetKeyDown(KeyCode.E))
    28.             {
    29.                 //SceneManagement.LoadScene("youcancallmesus");
    30.                 sceneToLoad = "youcancallmesus";
    31.                 enterAllowed = true;
    32.             }
    33.            
    34.         }
    35. }
    36.  
     
  25. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    214
    I'll give you a hint, something looks wrong in your if statement within the OnTriggerEnter2D, looks to be assigning, rather than using the equality operator :p also renderer.enabled would be equal to true if it were so, so there's no need to even write it using the equality operator, hopefully you see what I mean.
     
  26. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    How do i fix this?
    it is needed because the renderer gets disabled when the character moves too far away + by default its disabled as well
     
  27. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    214
    So you'd either write:
    Code (CSharp):
    1. if (renderer.enabled == true && Input.GetKeyDown(KeyCode.E))
    or simply:

    Code (CSharp):
    1. if (renderer.enabled && Input.GetKeyDown(KeyCode.E))
    As long as you understand why that's different, if not then look at assigning vs the equality operator. Might help to have a basic understanding of coding, so understanding basic things like if statements, functions, loops etc if you don't already :)
     
  28. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    Yes i understand how its different but it doesn't work, its still the exact same (nothing happens when E is pressed) but still thanks for trying :)
     
  29. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    214
    Stick a Debug.Log("here") within the if statement, then go to your console and see if it outputs "here" when you're inside the E and you're pressing E.
     
  30. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    debug.log / console never works for me idk why
     

    Attached Files:

  31. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    and there is also this
     

    Attached Files:

  32. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    214
    What do you mean it never works for you? If you Debug.Log("log working!") in your start function, does nothing show in console?

    That warning message is just saying you're assigning the value, but you're never actually using it.
     
  33. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    idk, the console is just always empty even if i use debug.log
    ah ok ty
     
  34. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    214
    Show me what you have written in the start function :)
     
  35. BlinMaster1000

    BlinMaster1000

    Joined:
    Sep 12, 2022
    Posts:
    21
    im not sure what u meant by the "start function" but here is the entire code :)
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. public class ToScene2 : MonoBehaviour
    6. {
    7.     private Renderer renderer;
    8.     private bool enterAllowed;
    9.     private string sceneToLoad;
    10. //    public static void LoadScene(string youcancallmesus, SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.          renderer = GetComponent<Renderer>();
    15. //         SceneManager.LoadScene("youcancallmesus", LoadSceneMode.Additive);
    16.     }
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.      
    21.     }
    22.  
    23.      void OnTriggerEnter2D(Collider2D col)
    24.         {
    25.             if ((renderer.enabled = true) && Input.GetKeyDown(KeyCode.E))
    26.             {
    27.                 //SceneManagement.LoadScene("youcancallmesus");
    28.                 sceneToLoad = "youcancallmesus";
    29.                 enterAllowed = true;
    30.             }
    31.          
    32.         }
    33. }
    34.  
     
  36. NeilB133

    NeilB133

    Joined:
    May 30, 2022
    Posts:
    214
    I know it's probably not what you want to hear, but perhaps take a few lessons in Unity and C-sharp if you're unaware of what the Start function is, or even what a function is. Maybe just do some Googling to understand scripting in Unity. If you're just after the answers to a very specific issue, you're not going to get very far after this issue is resolved.

    Here's documentation to the Start function:
    https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html

    It was in here I was referring to adding a Debug.Log in order to see a log of something working in the console. Here is the documentation to Debug.Log:

    https://docs.unity3d.com/ScriptReference/Debug.Log.html