有一个带有子按钮的ScrollView,并且Text对象通过脚本来创建动态。第一次,按钮和文本是正常创建的,但是当您尝试销毁ScrollView并向其中添加按钮和文本时,不会再次创建它们。
if (GameObject.Find("ScrollViewUsers") != null)
{
Destroy(GameObject.Find("ScrollViewUsers"));
}
GameObject scrollView = Instantiate(GameObject.Find("ScrollViewUsersSample"), GameObject.Find("PanelFindFriends").transform, true);
scrollView.name = "ScrollViewUsers";
scrollView.GetComponent<RectTransform>().localPosition = new Vector3(0, -20, 0);
scrollView.GetComponent<RectTransform>().sizeDelta = new Vector2(GameObject.Find("PanelFindFriends").GetComponent<RectTransform>().sizeDelta.x, GameObject.Find("PanelFindFriends").GetComponent<RectTransform>().sizeDelta.y - 40);
scrollView.transform.Find("Viewport/ContentUsersSample").name = "ContentUsers";
Debug.Log("userList.Count=" + userList.Count);
float _y = 0;
foreach (KeyValuePair<int, string> user in userList)
{
Debug.Log("user=" + user.Value);
Instantiate(GameObject.Find("TextUser"), GameObject.Find("ContentUsers").transform, true);
GameObject.Find("TextUser(Clone)").name = "user_" + user.Value;
GameObject.Find("user_" + user.Value).GetComponent<Text>().text = user.Value;
GameObject.Find("user_" + user.Value).GetComponent<RectTransform>().localPosition = new Vector3(-25, y, 0);
Instantiate(GameObject.Find("ButtonAddUser"), GameObject.Find("ContentUsers").transform, true);
GameObject.Find("ButtonAddUser(Clone)").name = "addUser_" + user.Value;
GameObject.Find("addUser_" + user.Value).GetComponent<RectTransform>().localPosition = new Vector3(62, y, 0);
y -= 40;
_y += (GameObject.Find("user_" + user.Value).GetComponent<RectTransform>().sizeDelta.y + 20);
}
答案 0 :(得分:1)
以下是您所需的示例
List<string> userList = new List<string> { "User1", "User2", "User3" };
[SerializeField]
private Text TextUserPrefabRef;
[SerializeField]
private Button ButtonAddUserPrefabRef;
[SerializeField]
private GameObject ScrollViewUsersSamplePrefabRef;
[SerializeField]
private Transform PanelFindFriendsRef;
private Transform ContentUsers;
public void CreateNew ()
{
if (GameObject.Find("ScrollViewUsers") != null)
{
Debug.Log("Destroying");
Destroy(GameObject.Find("ScrollViewUsers"));
}
GameObject scrollView = Instantiate(ScrollViewUsersSamplePrefabRef, PanelFindFriendsRef);
scrollView.name = "ScrollViewUsers";
ContentUsers = scrollView.transform.Find("Viewport/ContentUsersSample");
ContentUsers.name = "ContentUsers";
foreach (string user in userList)
{
Debug.Log("user=" + user);
GameObject newTextUser = Instantiate (TextUserPrefabRef.gameObject, ContentUsers) as GameObject;
newTextUser.GetComponent<Text>().text = user;
GameObject newButton = Instantiate (ButtonAddUserPrefabRef.gameObject, ContentUsers);
newButton.name = "addUser_" + user;
}
}
然后对您的scrollView,AddUserButton和Text对象进行预制 并在检查器中分配它们。
答案 1 :(得分:0)
在foreach循环中,创建一个新变量,而不是GameObject.Find()。
例如:
var go = Instantiate(GameObject.Find("TextUser"), GameObject.Find("ContentUsers").transform, true);)
go.name = "...";
go.GetComponent<Text>().text = "...";