功能代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DelGameObject1 : MonoBehaviour
{
public string DelName = "Dropdown";
public List<GameObject> list;
public Transform dropdown;
public void GetTarget()
{
list = new List<GameObject>();
GetChildObj(transform, DelName, ref list);
if (list.Count > 0)
{
dropdown = list[0].transform;
}
}
public float itemWidth = 140f;
public float itemHeight = 100f;
public int itemTextSize = 48;
public float TemplateHeight = 1000f;
public float templateY = -70f;
public void SetData()
{
RectTransform content = dropdown.transform.Find("Template/Viewport/Content").GetComponent<RectTransform>();
content.anchoredPosition = Vector2.zero;
content.sizeDelta = new Vector2(0, itemHeight);
RectTransform template = content.parent.parent.GetComponent<RectTransform>();
template.sizeDelta = new Vector2(template.sizeDelta.x, TemplateHeight);
template.anchoredPosition = new Vector2(template.anchoredPosition.x, templateY);
RectTransform item = content.GetChild(0).GetComponent<RectTransform>();
VerticalLayoutGroup ver = GetAndAddComp<VerticalLayoutGroup>(content.gameObject);
//ver.childForceExpandHeight = false;
//ver.childForceExpandWidth = false;
//ver.childControlHeight = false;
//ver.childControlWidth = false;
ContentSizeFitter contenSize = GetAndAddComp<ContentSizeFitter>(content.gameObject);
//contenSize.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
Debug.Log(content.Find("Item").GetComponent<RectTransform>().sizeDelta);
item.sizeDelta = new Vector2(0, itemHeight);
item.Find("Item Label").GetComponent<Text>().fontSize = itemTextSize;
Debug.Log("设置完成!");
}
T GetAndAddComp<T>(GameObject go) where T: Component
{
if (go.GetComponent<T>())
{
Destroy(go.GetComponent<T>());
}
return null;
}
public void DelGameObj()
{
for (int i = 0; i < list.Count; i++)
{
// DestroyImmediate(list[i]);
list[i].SetActive(false);
}
list = null;
}
public static void GetChildObj(Transform Trans, string cname, ref List<GameObject> list)
{
for (int i = 0; i < Trans.childCount; i++)
{
GameObject t = Trans.GetChild(i).gameObject;
if (t.name == cname)
{
if (!list.Contains(t))
list.Add(t);
}
GetChildObj(Trans.GetChild(i), cname, ref list);
}
}
}
编辑器代码:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(DelGameObject1))]
public class DelGameObjEditor1 : Editor
{
DelGameObject1 delGameObject;
private void OnEnable()
{
delGameObject = target as DelGameObject1;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("获取"))
{
delGameObject.GetTarget();
}
if (GUILayout.Button("删除"))
{
delGameObject.DelGameObj();
}
if (GUILayout.Button("设置"))
{
delGameObject.SetData();
// EditorUtility.SetDirty(null);
// AssetDatabase.SaveAssets();
}
}
}