I have a list of gameObjects(NPCs) instantiating on a UI scrollable panel. I want to be able to click on their name and assign them to the building for example. here's what I have so far:
HumanPool playerPool;
[SerializeField] GameObject PlayerInfo;
[SerializeField] TextMeshProUGUI playerName;
[SerializeField] Transform SpawnPoint;
void Start()
{
playerPool = FindObjectOfType<HumanPool>();
}
void updateListOfHumans()
{
SpawnPoint.DetachChildren();
for (var i = 0; i < playerPool.Humans.Count; i )
{
Vector3 pos = new Vector3(0, 0, SpawnPoint.position.z);
playerName = PlayerInfo.GetComponentInChildren<TextMeshProUGUI>();
playerName.text = playerPool.Humans[i].name;
GameObject SpawnedItem = Instantiate(PlayerInfo, pos, SpawnPoint.rotation);
SpawnedItem.transform.SetParent(SpawnPoint, false);
}
}
void OnMouseDown()
{
updateListOfHumans();
}
I'm pretty sure that when I click on a playerName (child of a button) there should be an onClick() function that will do something. But I have no idea how to get that specific ID of a NPC and how to target him/her.
Here's also the relevant code from HumanPool:
List<Human> humans = new List<Human>();
public List<Human> Humans { get { return humans; } }
Humans are generated in a pure C# constructor class:
public class Human {
public string name;
public Human(string name)
{
this.name = name;
}}
Should I add an ID variable in a constructor class and target clicked NPC with that?
My biggest problem here is how to tell the next method which NPC is chosen from a list and and that he/she should go work in that building.
Sorry for the possibly bad explanation but I really hope it makes some sense of what I'm trying to do here... Quite new with Unity so any help would be greatly appreciated.
Thank You!
CodePudding user response:
Guess you are using a UI.Button
component.
In that case there is indeed the onClick
event you could simply add a callback to like e.g.
var human = playerPool.Humans[i];
var button = spawnedItem.GetComponentInChildren<Button>();
button.onClick.AddListener(() => OnClickedHuman(human));
// You also want to do this rather on the spawned item, not the prefab btw
var text = spawnedItem.GetComponentInChildren<TextMeshProUGUI>();
text.text = human.name;
and then have
private void OnClickedHuman (Human human)
{
// Do what you want with human
Debug.Log($"Clicked on {human.name}!", this);
}