Sniffle6
Sniffle6

Reputation: 149

Unity Click button

I'm trying to remove a gameObject from the world and a list using:

   Destroy(obj);
   itemsInInv.Remove(obj.gameObject);

But for some reason, it's reading my list.count as 0 every time I try to reference it threw a click event. If I use a key down and remove a specific item it works fine. But when I try to read my list threw a click event it returns 0 instead of the amount of items actually in the array

Like I can push 'Z' and get the Debug.Log(itemsInInv.Count) will say 15. Then I'll click the item to try and run the same Debug.Log(itemsInInv.Count) and it returns 0.

I've tried using the built in interface on the unity program. I tried using

items.GetComponent<Button>().onClick.AddListener(() => { useItem(); });

Which actually did work 100% fine for a little while then for some reason stopped working and won't work again no matter what I do lol.

I've tried using:

void OnDestroy()
{
    manager.GetComponent<UIManager>().Remove(this.gameObject);
    Debug.Log("remove" + manager.GetComponent<UIManager>().itemsInInv.Count);
}
public void OnPointerClick(PointerEventData eventData)
{
    Destroy(gameObject);
}

Also tried doing the remove in the same function as the click. Same problem. Idk how else this is possible to do it? Even if I create a boolean and have it set to false, then use the button to set it too true, it won't read as true when debugged.

What I'm pretty much asking is, how do I add a list of buttons to the screen. Then delete the SAME button I clicked on from the screen and the list.

Upvotes: 0

Views: 1401

Answers (2)

Sniffle6
Sniffle6

Reputation: 149

Soo this is what i did to get it too work....

i added this script onto my item thats being clicked

public void OnPointerClick(PointerEventData eventData)
{
    EventSystem.current.SetSelectedGameObject(gameObject);
    Debug.Log("hey"+ EventSystem.current.currentSelectedGameObject);
}

then in my other script im running

            items.GetComponent<Button>().onClick.AddListener(() => { useItem(); });

which runs

public void useItem()
{
    Invoke("itemUsed", 0.25f);
}

which runs after 0.25

void itemUsed()
{
    Debug.Log(EventSystem.current.currentSelectedGameObject);
    deleteItem(EventSystem.current.currentSelectedGameObject);
    sortItems();
}

I had to do the invoke because it was calling useItem, before the currently selected was being selected

Also my event System was a child of my canvas which made my gameManager unable to access it the way i was

Upvotes: 1

xplatinumx15
xplatinumx15

Reputation: 101

Dont use a list. Use a Dictionary.

public static Dictionary<string, GameObject> dict = new Dictionary<string, GameObject>();

then you can use the gameobjects name.

foreach(GameObject r in FindObjectsOfType(typeof(GameObject)))
{
      dict.Add(r.name, r);
}

Then you can do

Destroy(gameObject.name);
dict.Remove(gameObject.name);

Upvotes: 0

Related Questions