Detecting a button click
I'm trying to spawn a unit in a 2D turn based war game, but the unfortunate reality is the On-click command doesn't work, it's included in the code below but it is completely dis-functional
does anyone know why i can;t use the On-click method here?
Code is included below with comments to highlight problem code
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerBehavior : MonoBehaviour {
//public bool PlayersTurn;
//public int ActionsPerTurn;
public BoardManager boardManager;
private Vector2 SelectedPosition;
private GameObject Mbutton;
private GameObject Bbutton;
private GameObject Abutton;
//private bool enemysTurn;
void Start () {
boardManager = GetComponent<BoardManager> ();
Mbutton = GameObject.FindGameObjectWithTag("SpawnMsoldier");
Abutton = GameObject.FindGameObjectWithTag("SpawnAsoldier");
Bbutton = GameObject.FindGameObjectWithTag("SpawnBSoldier");
Mbutton.gameObject.SetActive(false);
Bbutton.gameObject.SetActive(false);
Abutton.gameObject.SetActive(false);
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
ClickSelect();
Debug.Log(ClickSelect());
if (ClickSelect() == GameObject.FindGameObjectWithTag("PlayerHQ"))
{
Mbutton.gameObject.SetActive(true);
Bbutton.gameObject.SetActive(true);
Abutton.gameObject.SetActive(true);
//This is the problem code, for some reason, onClick is not useable
if (Mbutton.onClick == true)
{
Debug.Log("Testing..");
Instantiate (boardManager.PlayerUnits[3],new Vector3 (1,1,0f),Quaternion.identity);
}
}
if (ClickSelect() != GameObject.FindGameObjectWithTag("PlayerHQ"))
{
Mbutton.gameObject.SetActive(false);
Bbutton.gameObject.SetActive(false);
Abutton.gameObject.SetActive(false);
}
}
}
GameObject ClickSelect()
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit)
{
Debug.Log(hit.transform.name);
return hit.transform.gameObject;
}
else return null;
}
}
Comment
Answer by M-Hanssen · May 09, 2016 at 03:08 PM
private GameObject Mbutton;
Should be:
private Button Mbutton;
And initialize them with:
Mbutton = FindGameObjectWithTag("SpawnMsoldier").GetComponent<Button>();
Notice that "FindGameObjectWithTag" in general is bad practice. Use the inspector to fill the button as public variable or make sure the button has a unique script on it, so you can find it by type.