遍历存储所有物体添加到列表中(使用GameObject.activeSelf进行判断)

本文介绍了一个使用Unity实现的游戏或应用菜单管理方法,包括如何存储菜单项到列表中,并提供了隐藏所有子菜单的功能。通过查找带有特定组件的游戏对象来实现菜单项的管理和显示控制。

//存储菜单列表
List<GameObject> subMenu = new List<GameObject>();

//存储所有子菜单
public void StoreSubMenuData()
{
  var menu = mainMenuScreen.transform.FindChild("back/menuPanel");
  foreach (Transform kk in menu)
  {
    if (kk.GetComponent<Image>() != null && kk.GetComponent<Button>() == null)
    {
      subMenu.Add(kk.gameObject);
    }
  }
}
//隐藏所有子菜单
public void HideSubMenu()
{
  foreach (GameObject obj in subMenu)
  { if (obj.activeSelf == true)     {       obj.SetActive(false);     }
  }
}

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Weapon : MonoBehaviour { public List<WeaponStats> stats; public int weaponLevel; [HideInInspector] public bool statsUpdated; public Sprite icon; public void LevelUp() { if (weaponLevel < stats.Count - 1) { weaponLevel++; statsUpdated = true; if (weaponLevel >= stats.Count - 1)//如果武器满级了,会添加到满级武器列表 { PlayerController.instance.fullyLevelledWeapons.Add(this); PlayerController.instance.assignWeapons.Remove(this); } } } } [System.Serializable] public class WeaponStats { //速度,伤害,范围,攻击间隔,数量,持续时间 public float speed, damage, range, timeBetweenAttacks, amount, duration; public string upgradeText; } using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using UnityEngine; public class PlayerController : MonoBehaviour { public static PlayerController instance; private void Awake() { instance = this; } public float moveSpeed; public Animator anim; public float pickupRange = 1.5f; //public Weapon activeWeapon; public List<Weapon> unassignedWeapons, assignWeapons; public int maxWeapons; [HideInInspector] public List<Weapon> fullyLevelledWeapons = new List<Weapon>();//满级武器列表,武器满级时会添加到这个列表 void Start() { if (assignWeapons.Count == 0) //选择武器,1到容器长度 { AddWeapon(Random.Range(0, unassignedWeapons.Count)); } moveSpeed = PlayerStatController.instance.moveSpeed[0].value; pickupRange = PlayerStatController.instance.pickupRange[0].value; maxWeapons = Mathf.RoundToInt(PlayerStatController.instance.maxWeapons[0].value); } // Update is called once per frame void Update() { Vector3 moveInput = new Vector3(0f, 0f, 0f); moveInput.x = Input.GetAxisRaw("Horizontal"); moveInput.y = Input.GetAxisRaw("Vertical"); //Debug.Log(moveInput); moveInput.Normalize(); transform.position += moveInput * moveSpeed * Time.deltaTime; if (moveInput != Vector3.zero) { anim.SetBool("isMoving", true); } else { anim.SetBool("isMoving", false); } } public void AddWeapon(int weaponNumber)//分配武器 { if (weaponNumber < unassignedWeapons.Count) { assignWeapons.Add(unassignedWeapons[weaponNumber]); unassignedWeapons[weaponNumber].gameObject.SetActive(true); unassignedWeapons.RemoveAt(weaponNumber); } } public void AddWeapon(Weapon weaponToAdd)//遇到新武器后,添加解锁武器 { weaponToAdd.gameObject.SetActive(true); assignWeapons.Add(weaponToAdd); unassignedWeapons.Remove(weaponToAdd); } } using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class LevelUpSelectionButton : MonoBehaviour { public TMP_Text upgradeDescText,nameLevelText; public Image weaponIcon; private Weapon assignWeapon; public void UpdataButtonDisplay(Weapon theWeapon) { if(theWeapon.gameObject.activeSelf == true) { upgradeDescText.text = theWeapon.stats[theWeapon.weaponLevel].upgradeText; weaponIcon.sprite = theWeapon.icon; nameLevelText.text = theWeapon.name + " - Lvl " + theWeapon.weaponLevel; }else { upgradeDescText.text = "Unlock " + theWeapon.name; weaponIcon.sprite = theWeapon.icon; nameLevelText.text = theWeapon.name; } assignWeapon = theWeapon; } public void SelectUpgrade() { if(assignWeapon != null) { if(assignWeapon.gameObject.activeSelf == true) { assignWeapon.LevelUp(); }else { PlayerController.instance.AddWeapon(assignWeapon); } UIController.instance.levelUpPanel.SetActive(false); Time.timeScale = 1f; } } } 这是unity游戏的代码,已经实现了武器的解锁和升级现在需要你完善和完成以下功能,假如小怪能掉落7种道具(也可以是9种,可以修改),每个道具都含有数量,sprite,和name,道具会是预制体,然后玩家能够拾取道具,道具种类数量和每种道具的数量达到要求后才可以解锁或升级武器
08-20
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using System.Linq; using UnityEngine.Networking; using System.Collections; using System.IO; public class CSVFilter : MonoBehaviour { [Header("UI 组件")] [SerializeField] private InputField searchInput; [SerializeField] private RectTransform optionsContainer; [SerializeField] private GameObject optionButtonPrefab; [SerializeField] private ScrollRect scrollRect; [Header("CSV 数据")] [Tooltip("StreamingAssets 文件夹中的 CSV 文件名")] [SerializeField] private string csvFileName = "email.csv"; [Tooltip("是否跳过第一行标题行")] [SerializeField] private bool skipHeaderRow = true; [Header("性能设置")] [Tooltip("输入延迟后执行搜索的时间(秒)")] [SerializeField] private float searchDelay = 0.3f; [Tooltip("最大显示结果数量")] [SerializeField] private int maxResults = 50; // 私有数据字段 private Dictionary<string, string> uniqueDataMap = new Dictionary<string, string>(); // 存储原始大小写数据 private List<GameObject> activeButtons = new List<GameObject>(); private float lastInputTime; private string lastSearchTerm = ""; public bool click = false; private bool isDataLoaded = false; IEnumerator Start() { if (searchInput == null) Debug.LogError("SearchInput 未分配!请在Inspector中赋值"); if (optionsContainer == null) Debug.LogError("OptionsContainer 未分配!"); if (optionButtonPrefab == null) Debug.LogError("OptionButtonPrefab 未分配!"); if (scrollRect == null) Debug.LogError("ScrollRect 未分配!"); searchInput.interactable = false; yield return StartCoroutine(LoadCSVData()); searchInput.onValueChanged.AddListener(OnInputChanged); optionsContainer.gameObject.SetActive(false); searchInput.interactable = true; isDataLoaded = true; } void Update() { if (!isDataLoaded) return; if (Time.time - lastInputTime > searchDelay && !string.IsNullOrEmpty(lastSearchTerm)) { FilterOptions(lastSearchTerm); lastSearchTerm = ""; } // 控制滚动区域显示 scrollRect.gameObject.SetActive(optionsContainer.transform.childCount > 0 && !click); } /// <summary> /// 从CSV加载数据并去重(保留原始大小写) /// </summary> private IEnumerator LoadCSVData() { string filePath = Path.Combine(Application.streamingAssetsPath, csvFileName); // 特殊处理WebGL平台 #if UNITY_WEBGL && !UNITY_EDITOR UnityWebRequest www = UnityWebRequest.Get(filePath); yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.LogError($"CSV 加载失败: {www.error}"); yield break; } ParseCSVData(www.downloadHandler.text); #else if (!File.Exists(filePath)) { Debug.LogError($"CSV 文件不存在: {filePath}"); yield break; } string csvText = File.ReadAllText(filePath); ParseCSVData(csvText); #endif } /// <summary> /// 解析CSV数据并去重(保留原始大小写) /// </summary> private void ParseCSVData(string csvText) { uniqueDataMap.Clear(); string[] lines = csvText.Split( new[] { "\r\n", "\r", "\n" }, System.StringSplitOptions.RemoveEmptyEntries ); int startIndex = skipHeaderRow ? 1 : 0; for (int i = startIndex; i < lines.Length; i++) { string originalLine = lines[i].Trim(); if (string.IsNullOrWhiteSpace(originalLine)) continue; // 使用小写版本作为键 string normalizedKey = originalLine.ToLowerInvariant(); // 如果键不存在,添加原始大小写数据 if (!uniqueDataMap.ContainsKey(normalizedKey)) { uniqueDataMap.Add(normalizedKey, originalLine); } } Debug.Log($"成功加载 {uniqueDataMap.Count} 条唯一数据(保留原始大小写)"); } /// <summary> /// 输入框内容变化回调 /// </summary> void OnInputChanged(string value) { lastInputTime = Time.time; lastSearchTerm = value; click = false; if (string.IsNullOrEmpty(value)) { optionsContainer.gameObject.SetActive(false); ClearActiveButtons(); return; } optionsContainer.gameObject.SetActive(true); } /// <summary> /// 过滤并显示选项(保留原始大小写) /// </summary> void FilterOptions(string searchTerm) { ClearActiveButtons(); try { string normalizedSearchTerm = searchTerm.ToLowerInvariant(); // 获取所有匹配的键 var filteredKeys = uniqueDataMap.Keys .Where(key => key.Contains(normalizedSearchTerm)) .ToList(); // 检查是否只有一个匹配项且与输入内容相同 if (filteredKeys.Count == 1) { string matchedOriginal = uniqueDataMap[filteredKeys[0]]; // 不区分大小写比较 if (string.Equals(matchedOriginal, searchInput.text, System.StringComparison.OrdinalIgnoreCase)) { // 完全匹配唯一选项,关闭选项容器 optionsContainer.gameObject.SetActive(false); return; } } // 限制显示数量 var displayKeys = filteredKeys.Take(maxResults); // 创建选项按钮(使用原始大小写数据) foreach (string key in displayKeys) { GameObject buttonObj = Instantiate(optionButtonPrefab, optionsContainer); buttonObj.GetComponentInChildren<Text>().text = uniqueDataMap[key]; // 使用原始大小写 Button button = buttonObj.GetComponent<Button>(); button.onClick.AddListener(() => OnOptionSelected(uniqueDataMap[key])); activeButtons.Add(buttonObj); } // 更新容器布局 LayoutRebuilder.ForceRebuildLayoutImmediate(optionsContainer); scrollRect.verticalNormalizedPosition = 1f; } catch (System.Exception e) { Debug.LogError($"搜索失败: {e.Message}"); } } /// <summary> /// 选项点击处理 /// </summary> void OnOptionSelected(string selectedText) { searchInput.text = selectedText; // 保持原始大小写 optionsContainer.gameObject.SetActive(false); ClearActiveButtons(); click = true; } /// <summary> /// 清理生成的按钮 /// </summary> void ClearActiveButtons() { foreach (GameObject button in activeButtons) { if (button != null) Destroy(button); } activeButtons.Clear(); } /// <summary> /// 编辑器重置时清理资源 /// </summary> void OnDestroy() { ClearActiveButtons(); if (searchInput != null) { searchInput.onValueChanged.RemoveListener(OnInputChanged); } } /// <summary> /// 重新加载 CSV 数据 /// </summary> public void ReloadCSVData() { StartCoroutine(ReloadCSVDataCoroutine()); } private IEnumerator ReloadCSVDataCoroutine() { isDataLoaded = false; searchInput.interactable = false; ClearActiveButtons(); optionsContainer.gameObject.SetActive(false); yield return StartCoroutine(LoadCSVData()); searchInput.interactable = true; isDataLoaded = true; } } unity 使用以上代碼,當點擊除了inputfield 和scroll rect 之外的地方,關閉scrollrect
最新发布
11-27
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值