Unity中如何为AlertView的Rate按钮设置OnClick事件?
Hey there! Let's get that Rate button working properly. Looking at your code, you're already on the right track by passing a callback delegate to showAlertDialog—that's exactly where we'll handle the button clicks.
First, let's break down what's happening: the (int obj) parameter in your callback is almost certainly the index of the button that was clicked. In your string array, the last two entries are your button texts: "Rate" and "Maybe Later". Most dialog systems map these to index 0 and 1 respectively (so clicking "Rate" sends 0, "Maybe Later" sends 1—you might want to double-check your showAlertDialog implementation to confirm this mapping, but let's run with this assumption for now).
Here's how to update your code to add the Rate button's OnClick logic:
if (Input.GetMouseButtonDown(0)) { showAlertDialog( new string[] { "Rate Us", "Take 2 min to rate our app", "Rate", "Maybe Later" }, (int obj) => { // Check which button was clicked if (obj == 0) // This should correspond to the "Rate" button { // Put your Rate button logic right here! Debug.Log("Rate button clicked! Let's send the user to the app store."); // Example action: Open your app's store page // Application.OpenURL("your-app-store-url-here"); } else if (obj == 1) // "Maybe Later" button { Debug.Log("User chose to rate later—closing dialog."); // Add logic to dismiss the dialog if your system doesn't do this automatically } Debug.Log("Local Handler called: " + obj); }); }
Quick Notes to Verify:
- If the callback's
objvalue doesn't match 0 for Rate, check how yourshowAlertDialogfunction is set up. For example, if it passes the array index of the button text (so "Rate" is index 2 of your string array), adjust the conditional toobj == 2instead. - If you built the
showAlertDialogfunction yourself, make sure it's triggering the callback with the correct index when each button is clicked. Here's a quick snippet of how that might look inside your dialog script:
public void showAlertDialog(string[] dialogData, Action<int> onButtonClicked) { // Grab references to your UI buttons (set these up in the Inspector or via code) Button rateBtn = transform.Find("RateButton").GetComponent<Button>(); Button laterBtn = transform.Find("LaterButton").GetComponent<Button>(); rateBtn.onClick.AddListener(() => { onButtonClicked?.Invoke(0); // Pass 0 when Rate is clicked Destroy(gameObject); // Close the dialog }); laterBtn.onClick.AddListener(() => { onButtonClicked?.Invoke(1); // Pass 1 when Maybe Later is clicked Destroy(gameObject); // Close the dialog }); // Set title and message text here using dialogData[0] and dialogData[1] }
That's all there is to it! Just drop your specific Rate-related logic (like opening the app store, showing a thank-you message, etc.) inside that if (obj == 0) block, and you're good to go.
内容的提问来源于stack exchange,提问作者developer

