hello im pretty new to unity, im having a problem where i have 4 square buttons on my canvas and 4 characters in the game, each button should move one character by dragging on the button itself, updating an X and Y variable and with this variable calculating the direction. the problem is that any button i touch updates the pair of variables for all of them instead of the only one i touched. looking on internet i found that it may be something with the event system but i have no idea how to properly set it up.
1 Answer
This can be solved easily by creating a function MoveThecharacter(Character char) (where every character is having a script Character.cs or else just pass a gameobject MoveTheCharacter(GameObject character))
Manually set the button listeners to each button
Drag in the gameobject to which this script is attached and in the dropdown, select the script which opens a bunch of public functions in that script.
Select MoveTheCharacter(GameObject character) from the list and drag and drop the character gameobject.
Hence every time the button is pressed, the function MoveTheCharacter(GameOject character) is called and the argument that got passed into this function is the one that was dragged and dropped into the slot by the user. Hence, update the coordinates of this gameobject in this function.
More reliable with adding button listeners in the script:
If you want a button to update the X and Y coordinates of its respective player, then you need to have a pair of a Button and a Player. For that, create a dictionary of Button as key and Character (or GameObject) as its value.
public Dictionary<Button, GameObject> pairs = new Dictionary<Button, GameObject>();
Now add ButtonListeners to these buttons and pass its respective player as an argument.
foreach (var pair in pairs) {
pair.Key.onClick.AddListener(() => MoveThisCharacter(pair.Value));
}
void MoveThisCharacter(GameObject character) {
// move this character
}


