i have UI interact button and its disable at first when player collide with object it get active
if you click the button the script will run … the problem is when you collide with another object
and click the button the last script and the new script running together …
the on collision enter 2d is on the objects and its detecte player enter.
here is a picture to get confused like me.
Okay , from looking at the code i think you’re misunderstanding how AddListener/RemoveListener work , so here’s a short/basic explanation :
the button has a list of “functions” (callbacks) that it saves internally, you use AddListener to add your method , so basically you tell the button “Take this method and add it to the list of methods to execute whenever you get clicked”
An important thing to note is that AddListener doesn’t check if the method is added already or not , so if you add “Save” 10000 times (spoiler alert), next time you click it will call “Save” 10000 times
Also , there is a RemoveListener
Now , what you’re doing there is toggling Detect to true when you enter the trigger , and from there until you exit the trigger you’re adding your method every frame , so for example if you enter the trigger , wait 1000 frames ( about a minute if you’re running 60fps) , then click the button , it will run your Save method 1000 times.
A simple fix would be to listen on enter , and remove on exit , simple and clean , maybe something like this.
using UnityEngine;
using UnityEngine.UI;
public class Check_Point : MonoBehaviour
{
private GameObject Interact_button;
private Button IntButton;
public GameObject Player;
public Vector2 Pos;
private void Awake()
{
Interact_button = GameObject.Find("Interact_Parents").transform.GetChild(0).gameObject;
IntButton = Interact_button.GetComponent<Button>();
}
private void Save()
{
Debug.Log("Test");
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Interact_button.SetActive(true);
Player = other.gameObject;
IntButton.onClick.AddListener(Save);
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Interact_button.SetActive(false);
Player = null;
IntButton.onClick.RemoveListener(Save);
}
}
}