Change Button's Object via script

Viewed 18

Is there a way to change the object via script? I've got 4 Npcs that they each have the same scripts in but different parent. right now I'm dragging the npc from editor but because of that the button always knows only one Npc and the other gets index error (trying to add object to list). any way to switch it depending on raycast? or other ways? thank you.

enter image description here

1 Answers

The best way to do this is to set the event from within the code. The code can systematically control the buttons. So create a script manager and add events to it like the tips below.

public class ButtonManager : MonoBehaviour
{
    private Button[] buttons; // Add buttons here

    public Transform targetPlayer; // something for e.g

    private void Start()
    {
        foreach (var button in buttons)
        {
            button.onClick.AddListener(() =>
            {
                /// here you can write your actions..

                Debug.Log(targetPlayer.name);
            });
        }
    }
}

You can also use the remove Listener code to delete events.

buttons[index].onClick.RemoveAllListeners();
Related