Ill try to explain my issue. I need to do for my school project simple 2D escape room. I've got most of the scripts ready, when I click an item he add to the inventory list, and then I can see it on my inventory bar. The problem is , I want that the buttons of the UI Bar inventory, to know after I click the item , to know what item I've been clicking on. the way I did worked half way because he always give the key item. Ive got State Machine Interface. that inheritance to 2 more scripts (that open or close the other interactive stuff (door drawer). got KeyItems script and Interactable Script and UImanager - Singleton. is there to it in a generic way? this is the PlayerCast Script that I add the items I click on to the inventory, thought the button need to be here
public enum item {none , paperclip , key }
public class PlayerCast : MonoBehaviour
{
public Camera cam;
public List<item> inventory;
public item activeItem;
private void Start()
{
inventory = new List<item>();
}
// Update is called once per frame
void Update()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.CompareTag("Interact"))
{
Interactable interactable = hit.collider.gameObject.GetComponent<Interactable>();
interactable.CLickMe(activeItem);
}
else if(hit.collider.CompareTag("Key"))
{
KeyItems hitItem = hit.collider.gameObject.GetComponent<KeyItems>();
hitItem.PickMeUp();
}
}
}
}
public void ButtonSelect() //this is the generic button im trying to do
{
this.activeItem = item.key;
Debug.Log("Clicked");
}
You need event.
public enum ItemTypes { None , Paperclip , Key }
[DisallowMultipleComponent]
public class Foo : MonoBehaviour {
// Action its void delegate
public event System.Action<ItemTypes> Selected;
public ItemTypes ActiveItem { get; private set; }; // property
public void ButtonSelect () {
ActiveItem = ItemTypes.Key;
Selected?.Invoke(ActiveItem); // invoke event
}
}
[DisallowMultipleComponent]
public class YourUIBar : MonoBehaviour {
[SerializeField] private Foo _foo; // link on inspector
private void OnEnable () {
ItemChange(Foo.ActiveItem); // setup current
Foo.Selected += ItemChange; // subscribe to event
}
private void OnDisable () {
Foo.Selected -= ItemChange;
}
private void ItemChange (ItemTypes item) {
// your code
}
}