简体   繁体   中英

Find a GameObject and check if the user has clicked on it

I have recently been making the UI for a game I am creating and have run into a problem. I have been trying to find a way in the new Unity 4.6 for the user to be able to click on a player card and have it select the player they clicked on.

public void Panel1Click()
{
    GameManager.Player1Select ();
}

This is the way I am doing it at the moment, calling this when the player clicks on Panel 1, there are also 3 more for each of them.

I have been researching different methods on how to find the object the player clicks the execute the correct selecting code.

if (GameObject.Find ("Panel 1")) 
{
    print ("Click Panel 1");
    GameManager.Player1Select();
} 

This is one of the methods I tried, however nothing gets called. (Because it just checks if the object exists/is true? I think).

All these methods are linked to the EventSystem component on the panels.

Is there a more efficient way of condensing all the functions and just checking which panel the player clicks on?

You can actually have one parameter for your click handler. Supported types are: int , float , string and object reference . So you can define your handler like this:

public void SelectCharacter(int character) {
    GameManager.PlayerSelect(character)
}

Then just set the parameter in the event trigger.

You can add a collider to the game object (sprite), and then in the OnMouseDown function to test if it is clicked.

Select the card --> Add a box collider to it --> Add a MonoBehaviour script and attach to the card --> In the script, add function:

 bool bClicked = false;
 void OnMouseDown()
 {
     Debug.Log(gameObject.name + " is clicked");        
     bClicked = true;
 }

Create a script and put it on the object(Panel) you want to interact with, then try this code. In this example it finds the parent panel and sets it to inactive

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

public class CloseInventory : MonoBehaviour, IPointerDownHandler
{
    GameObject inventoryPanel;

    // Use this for initialization
    void Start()
    {
        inventoryPanel = GameObject.Find("Inventory Panel");
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        //SET WHAT TO DO HERE
        inventoryPanel.SetActive(false);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM