OnTriggerEnter2D with if/else

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?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnableDisable : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        //for testing
        if (Input.GetKeyDown(KeyCode.X)) {
        GetComponent<Renderer>().enabled = false;
        }
    }
   
    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject)
    {
        GetComponent<Renderer>().enabled = true;
    }
        else
    {
        GetComponent<Renderer>().enabled = false;
    }
}
}
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: How do I make a key appear?

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

Thanks.

1 Like

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:)

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.

i’ve seen that happen in alot of other fora (also unity) so ur straight cappin’

What?

i’ve seen people get helped step by step on unity formum is what i meant by my last msg

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:

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 :slight_smile: (except for creditcard details LOL)

8439365--1118282--afbeelding_2022-09-14_153242279.png

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.

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

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. :frowning:

the “as i said” was meant for the sentence next to it not for the Rigidbody part :frowning:
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:(

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.

i will read them thanks for trying to help me and i’m sorry for my noobness

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. :slight_smile:

Good luck.

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 :slight_smile:

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:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
  
    public class EnableDisable : MonoBehaviour
    {
        private Renderer renderer;

        // Start is called before the first frame update
        void Start()
        {
            renderer = GetComponent<Renderer>();
        }
  
        // Update is called once per frame
        void Update()
        {
            //for testing
            if (Input.GetKeyDown(KeyCode.X))
            {
                renderer.enabled = false;
            }
        }
    
        void OnTriggerEnter2D(Collider2D col)
        {
            Debug.Log("OnTriggerEnter2D called!")
            renderer.enabled = true;
        }

        void OnTriggerExit2D(Collider2D col)
        {
            Debug.Log("OnTriggerExit2D called!")
            renderer.enabled = false;
        }
    }

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.

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:

2 Likes

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 :):):):):):):):slight_smile:

1 Like