how to link URL into multiple buttons in a condition "if"
I've been struggling with my AR project in Unity. The main problem is the button opens the link repeatedly and it won't stop. The concept I want to reach here is when I scanned a marker, a description text will pop up along with the button, the button will take user to a URL. The code I'm using is
public Transform ButtonMap;
TextObjectName.GetComponent().text=name;
if (name == "QRCode1"){ ButtonMap.GetComponent.().onClick.AddListener(delegate {Application.OpenURL("https://www.google.com"); }); }
if (name == "QRCode2"){ ButtonMap.GetComponent.().onClick.AddListener(delegate {Application.OpenURL("https://www.facebook.com"); }); }
Answer by KoenigX3 · Mar 31, 2021 at 01:32 PM
When two if conditions are mutually exclusive, you should use else if. This way, if the first condition is true, it will not evaluate the second condition, saving you both time and resources.
The actual problem here is that whenever this code runs, it adds the listener again, even if it was added already. A solution would be to use RemoveListener or RemoveAllListeners to ensure that this delegate is added only once.
ButtonMap.GetComponent<Button>().onClick.RemoveAllListeners();
if(name == "QRCode1")
{
// Add google.com as you did
}
else if(name == "QRCode2")
{
// Add facebook.com as you did
}
Your answer
Follow this Question
Related Questions
How to smooth this jumping script? 1 Answer
Logic for a lot of animations 0 Answers
WHY !! CountDown not Working inside the IF Conndition !!! 2 Answers
Crossfadeanimations dont play 0 Answers