我有一個在 UI 可滾動面板上實體化的游戲物件(NPC)串列。例如,我希望能夠點擊他們的名字并將他們分配給建筑物。這是我到目前為止所擁有的:
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();
}
我很確定當我點擊 playerName (按鈕的子級)時,應該有一個 onClick() 函式可以做一些事情。但我不知道如何獲得 NPC 的特定 ID 以及如何針對他/她。
這里還有來自 HumanPool 的相關代碼:
List<Human> humans = new List<Human>();
public List<Human> Humans { get { return humans; } }
人類是在純 C# 建構式類中生成的:
public class Human {
public string name;
public Human(string name)
{
this.name = name;
}}
我應該在建構式類中添加一個 ID 變數并用它來定位點擊的 NPC 嗎?
我在這里最大的問題是如何告訴下一個方法從串列中選擇哪個 NPC 以及他/她應該去那個建筑物作業。
抱歉,可能有錯誤的解釋,但我真的希望它能對我在這里嘗試做的事情有所了解...... Unity 非常新,所以任何幫助都將不勝感激。
謝謝你!
uj5u.com熱心網友回復:
猜猜你正在使用一個UI.Button組件。
在這種情況下,確實存在onClick您可以簡單地添加回呼的事件,例如
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;
然后有
private void OnClickedHuman (Human human)
{
// Do what you want with human
Debug.Log($"Clicked on {human.name}!", this);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340628.html
