using CardGameDisplayer; using CGGame; using CGGame.GameData.Cards; using…
- User
using CardGameDisplayer; using CGGame; using CGGame.GameData.Cards; using CGGame.GameData.Skills; using CGGame.Textures; using FullSerializer; using QFramework; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using CGGame.UIComponent; using TMPro; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.UI; public class CardEditorScene : BaseScene, IController, ICanSendEvent { public string avatarsPath = System.Environment.CurrentDirectory + "/Avatars/"; //path to game files.; public string cardsPath = System.Environment.CurrentDirectory + "/Cards"; //path to game files.;
public Transform humanCreatedCardPosition; public Transform aiGeneratedCardPosition; public Slider[] Sliders; public ValueDropDown[] Dropdowns; public TextMeshProUGUI[] Labels; public Toggle TauntToggle; public TMP_InputField nameInputField; public Button CardImageButton; [SerializeField] public TMP_Dropdown cardTypeDropdown; [SerializeField] public TMP_Dropdown cardClassDropdown; [SerializeField] private GameObject currentMinionCardPrefab; [SerializeField] private GameObject currentMagicCardPrefab; [SerializeField] private GameObject currentTrapCardPrefab; [SerializeField] private GameObject cardListContent; [SerializeField] private GameObject cardListItemPrefab; [SerializeField] private GameObject cardListAddCardItemPrefab; [SerializeField] private BagWindow bagWindow; [SerializeField] private TextMeshProUGUI errorText; [SerializeField] private TMP_InputField backgroundStoryText; // Update is called once per frame [SerializeField] private TestLoopScrollView loopScrollView; private GameObject createCardItem; private CardButton currentCardButton; [HideInInspector] private GameObject currentCardPrefab; private CardDisplayer currentCardDisplayer; private int _attackValue; private int _healthValue; private int _costValue; public MenuButton generateBtn; public MenuButton saveGenertedCardBtn; [SerializeField] private AiPrompt _prompt; public TMP_InputField _promptInputField; public BaseCard generatedCard; protected override void Awake() { } // Start is called before the first frame update protected override void Start() { base.Start(); createCardItem = Instantiate(cardListAddCardItemPrefab, cardListContent.transform, false) as GameObject; createCardItem.GetComponent<CreateCardButton>().scene = this; InitComponents(); // Ai this.RegisterEvent<GenerateAiCardEvent>(OnAiGenerateCard).UnRegisterWhenGameObjectDestroyed(gameObject); generateBtn.onClickEvent.AddListener(() => { this.GetSystem<ISoundSystem>().PlaySound(SoundType.Button_Low); this.SendCommand(new GenerateAiCardCommand(this._prompt)); }); saveGenertedCardBtn.onClickEvent.AddListener(OnSaveGeneratedCardButtonPressed); _promptInputField.onValueChanged.AddListener((prompt) => { _prompt.rawPrompt[0].value = prompt; }); nameInputField.onValueChanged.AddListener(OnNameTextValueChanged); cardTypeDropdown.onValueChanged.AddListener(OnCardTypeDropDownChanged); cardClassDropdown.onValueChanged.AddListener(OnCardClassDropDownChanged); bagWindow.OnItemClicked += OnBagWindowItemClicked; this.RegisterEvent<CreateCardEvent>(OnCreateCard).UnRegisterWhenGameObjectDestroyed(gameObject); this.RegisterEvent<UpdateCardEvent>(OnUpdateCard).UnRegisterWhenGameObjectDestroyed(gameObject); this.RegisterEvent<DeleteCardEvent>(OnDeleteCard).UnRegisterWhenGameObjectDestroyed(gameObject); loopScrollView.Init(); UpdateCardListView(); } private void InitComponents() { foreach (ValueDropDown item in Dropdowns) { switch (item.name) { case "CostDropdown": item.GenerateNumberOptions(0,10); break; case "HealthDropdown": item.GenerateNumberOptions(0,15); break; case "AttackDropdown": item.GenerateNumberOptions(0,15); break; case "ClassDropdown": item.GenerateStringOptions(new List<string>(){"中立","法师","刺客"}); break; } item.onValueChanged.AddListener((int value) => OnDropDownValueChange(value, item)); }; } public void OnCreateCard(CreateCardEvent e) { currentCardButton.SetCard(e.mCard); currentCardButton.BindEvent(); } public void OnUpdateCard(UpdateCardEvent e) { if (!e.mIsAiGenerated) { currentCardButton.SetCard(e.mCard); } PreviewCard(e.mCard, e.mIsAiGenerated); } public void OnDeleteCard(DeleteCardEvent e) { Destroy(currentCardButton.gameObject); } public void OnAiGenerateCard(GenerateAiCardEvent e) { generatedCard = e.mCard; PreviewCard(e.mCard, true); } public void UpdateCardListView() { var cards = this.GetModel<IUserModel>().UserCreatedCards; foreach (var cardButton in FindObjectsOfType<CardButton>()) { Destroy(cardButton.gameObject); } foreach (var card in cards) { var go = Instantiate(cardListItemPrefab, cardListContent.transform, false); createCardItem.transform.SetAsLastSibling(); go.GetComponent<CardButton>().scene = this; go.GetComponent<CardButton>().SetCard(card); go.GetComponent<CardButton>().BindEvent(); } var firstDeckButton = cardListContent.GetComponentInChildren<CardButton>(); if (firstDeckButton != null) { SetActiveCard(firstDeckButton); } } public void OnBagWindowItemClicked(string avatarId) { currentCardButton.card.Avatar = avatarId; currentCardDisplayer.UpdateCardImage(currentCardButton.card.Type, avatarId); } void Update() { } public void CreateNewCard() { var go = Instantiate(cardListItemPrefab, cardListContent.transform, false) as GameObject; createCardItem.transform.SetAsLastSibling(); go.GetComponent<CardButton>().scene = this; BaseCard card = new BaseCard(); CGGame.CGDataTable.FillCard(card, new CGGame.CardID((int)CardTypes.MinionCard)); card.Name = "New Card"; var cardButton = go.GetComponent<CardButton>(); GameManager.Instance.config.playerCards.Add(card); cardButton.SetCard(card); SetActiveCard(cardButton); } public void CreateNewCardOnTop() { var go = Instantiate(cardListItemPrefab, cardListContent.transform, false) as GameObject; go.transform.SetAsFirstSibling(); go.GetComponent<CardButton>().scene = this; BaseCard card = new BaseCard(); CGGame.CGDataTable.FillCard(card, new CGGame.CardID((int)CardTypes.MinionCard)); card.Name = "New Card"; var cardButton = go.GetComponent<CardButton>(); GameManager.Instance.config.playerCards.Add(card); cardButton.SetCard(card); SetActiveCard(cardButton); } public void PreviewCard(BaseCard card,bool isGeneratedCard = false) { var cardType = card.Type; if (currentCardPrefab != null) { Destroy(currentCardPrefab); currentCardPrefab = null; } Transform cardPosition; if (isGeneratedCard) { cardPosition = aiGeneratedCardPosition; } else { cardPosition = humanCreatedCardPosition; } if (cardType == CardTypes.MinionCard) { currentCardPrefab = Instantiate(currentMinionCardPrefab, cardPosition.position, cardPosition.rotation); } else if (cardType == CardTypes.MagicCard) { //spell card has no keywords, so it can't be filtered. currentCardPrefab = Instantiate(currentMagicCardPrefab, cardPosition.position, cardPosition.rotation); } else if (cardType == CardTypes.TrapCard) { currentCardPrefab = Instantiate(currentTrapCardPrefab, cardPosition.position, cardPosition.rotation); } if (currentCardPrefab == null) { return; } currentCardPrefab.transform.SetParent(cardPosition.transform, true); currentCardDisplayer = currentCardPrefab.GetComponent<CardDisplayer>(); var draggable = currentCardPrefab.GetComponent<Dragable>(); Destroy(draggable); var timerColdDown = currentCardPrefab.GetComponent<TimerColdDown>(); Destroy(timerColdDown); var position = cardPosition.position; position.z = -1; var localScale = currentCardPrefab.transform.localScale; localScale = new Vector3(localScale.x * 0.8f, localScale.y * 0.8f, 1.0f); currentCardPrefab.transform.localScale = localScale; currentCardPrefab.transform.position = position; currentCardDisplayer.GetComponent<SortingGroup>().sortingLayerName = "Card"; currentCardDisplayer.GetComponent<SortingGroup>().sortingOrder = 1; currentCardDisplayer.ManualPositioning = true; var cardEditorCard = currentCardPrefab.AddComponent<CardEditorCard>(); cardEditorCard.scene = this; UpdateCardProperties(card); FilterKeyword(card); bagWindow.SetData(card.Type); currentCardDisplayer.SetCardData(card); } public void SetActiveCard(CardButton button) { if (currentCardButton != null) { currentCardButton.SetActive(false); } currentCardButton = button; currentCardButton.SetActive(true); PreviewCard(button.card); } public void SaveCard(CardButton button) { if (!checkProperties(button.card)) { OpenPopup<PopupOneButton>("PopupOneButton", popup => { popup.text.text = "卡牌" + button.card.Name + ": " + errorText.text + "请修改后再重新保存"; popup.buttonText.text = "OK"; popup.button.onClickEvent.AddListener(() => { popup.Close(); }); }); return; } SaveCardAvatar(button); bool needUpdate = GameManager.Instance.config.playerCards.Exists(x => x.id == button.card.id); if (needUpdate) { GameManager.Instance.config.playerCards.RemoveAll(x => x.id == button.card.id); } GameManager.Instance.config.playerCards.Add(button.card); GameManager.Instance.config.SaveCustomizedCards(); LogMessage("Save Card Sucessed!"); //SaveCardAvatar(button); //SaveCardData(button); } private void SaveCardAvatar(CardButton button) { if (!File.Exists(button.avatarPath)) return; var filename = button.card.Avatar + Path.GetExtension(button.avatarPath); var folderPath = Path.Combine(Application.dataPath, "Resources", "Avatars", "CustomizedCards"); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } var destFileName = string.Format("{0}/{1}", folderPath, filename); Debug.Log(destFileName); File.Copy(button.avatarPath, destFileName); //writeCaptureDataToFile(button.texture, avatarsPath, button.card.Id); //write card data to file. 创建一个文件夹并将保存的数据写入该文件夹中. } public void RemoveCard(CardButton button) { GameManager.Instance.config.playerCards.Remove(button.card); } public void UploadCardImage() { bagWindow.GetComponent<AutoHideControl>().PopupControl(); // Debug.Log("UploadCardImage"); // if (currentCardButton == null) // { // return; // } // BaseCard card = currentCardButton.card; // //创建一个文件扩展名列表 // List<string> extensions = new List<string>(); // List<string> twoDFileExtensions = new List<string> { "png", "jpg" }; // List<string> movieFileExtension = new List<string> { "mov", "mpg", "mpeg", "mp4", "avi", "asf", "mov" }; // //将两个文件扩展名添加到列表中 // extensions.AddRange(twoDFileExtensions); // //将电影文件扩展名添加到列表中 // extensions.AddRange(movieFileExtension); // //打开文件 // string path = FileBrowser.Instance.OpenSingleFile("Open file", "", "", //extensions.ToArray()); // if (string.IsNullOrEmpty(path)) // { // return; // } // //创建一个基础纹理 // BaseTexture texture; // //获取文件扩展名 // var extension = System.IO.Path.GetExtension(path).Replace(".", ""); ; // //如果是两个文件扩展名则将其转换为Texture // if (twoDFileExtensions.Contains(extension)) // { // byte[] data = FileBrowser.Instance.CurrentOpenSingleFileData; // texture = new TwoDTexture(data.CTToTexture()); // } // else // { // texture = new CGGame.Textures.MovieTexture("file://" + path); // } // card.Avatar = card.Id; // //currentCardButton.avatarPath = System.IO.Path.GetFileNameWithoutExtension(path).Trim(); //currentCardButton.SetAvatar(texture.GetPreview2D()); // currentCardButton.avatarPath = path; // TextureCollectionReader.Readers["Avatars"].ReadSingle(card.Avatar, texture); // //设置基础纹理 //currentCardDisplayer.UpdateCardImage(card.Avatar); } public void OnNameTextValueChanged(string value) { if (currentCardButton == null) { return; } currentCardButton.SetCardName(value); currentCardDisplayer.SetCardData(currentCardButton.card); } public void OnBackgroundStoryTextValueChanged(string value) { if (currentCardButton == null) { return; } BaseCard card = currentCardButton.card; card.BackgroundStory = value; currentCardDisplayer.SetCardData(card); } public void SetActiveKeyword(SkillListItem keywordListItem) { if (currentCardButton == null) { return; } BaseCard card = currentCardButton.card; card.effects = keywordListItem.Data.Effects ; card.skill = keywordListItem.Data; card.CardClass = keywordListItem.Data.CardClass; currentCardButton.SetDescription(keywordListItem.Data.EffectDesc); currentCardDisplayer.SetCardData(currentCardButton.card); } public void OnDropDownValueChange(int value, ValueDropDown eventSender) { if (currentCardButton == null) { return; } BaseCard card = currentCardButton.card; switch (eventSender.name) { case "AttackDropdown": card.Attack = value; break; case "HealthDropdown": if (value == 0) { value = 1; } card.Health = value; break; case "CostDropdown": card.Cost = value; UpdateHealthAndAttackScope(value,card.Health, card.Attack); break; case "ClassDropdown": card.CardClass = (CardClassTypes)(value - 1); // UpdateHealthAndAttackScope(value,card.Health, card.Attack); break; } eventSender.value = value; card.effects?.Clear(); FilterKeyword(card); currentCardButton.SetCard(card); currentCardDisplayer.SetCardData(card); } void UpdateHealthAndAttackScope(int costValue, int health, int attack) { var minHealthList = Enumerable.Repeat(0, 11).ToArray(); var maxHealthList = new[] { 3,5,7,10,13,15,15,15,15,15,15 }; var minAttackList = Enumerable.Repeat(0, 11).ToArray(); var maxAttackList = new[] { 0,1,2,4,5,7,9,11,13,15,15 }; var minHealthValue = minHealthList[costValue]; var maxHealthValue = maxHealthList[costValue]; var minAttackValue = minAttackList[costValue]; var maxAttackValue = maxAttackList[costValue]; foreach (ValueDropDown item in Dropdowns) { switch (item.name) { case "HealthDropdown": item.GenerateNumberOptions(minHealthValue,maxHealthValue); if (health >= maxHealthValue) { item.SetValueWithoutNotify(maxHealthValue); } else { item.SetValueWithoutNotify(health); } break; case "AttackDropdown": item.GenerateNumberOptions(minAttackValue,maxAttackValue); if (attack >= maxAttackValue) { item.SetValueWithoutNotify(maxAttackValue); } else { item.SetValueWithoutNotify(attack); } break; } item.RefreshShownValue(); }; } private bool checkProperties(BaseCard card) { if (card.Type == CardTypes.MinionCard) { return card.Cost * 2 - (card.Attack) - (card.Health) >= 0; } else{ errorText.gameObject.SetActive(false); } return true; } private void UpdateCardProperties(BaseCard card) { foreach (ValueDropDown item in Dropdowns) { switch (item.name) { case "AttackDropdown": item.SetValueWithoutNotify(card.Attack); item.gameObject.SetActive(card.Type == CardTypes.MinionCard); break; case "HealthDropdown": item.SetValueWithoutNotify(card.Health); item.gameObject.SetActive(card.Type == CardTypes.MinionCard); break; case "CostDropdown": item.SetValueWithoutNotify(card.Cost); break; case "ClassDropdown": item.SetValueWithoutNotify((int)card.CardClass + 1); break; } item.RefreshShownValue(); }; foreach (TextMeshProUGUI item in Labels) { switch (item.name) { case "AttackLabel": item.gameObject.SetActive(card.Type == CardTypes.MinionCard); break; case "HealthLabel": item.gameObject.SetActive(card.Type == CardTypes.MinionCard); break; } } nameInputField.text = card.Name; backgroundStoryText.text = card.BackgroundStory; cardTypeDropdown.value = (int)card.Type; // cardClassDropdown.value = (int)card.CardClass + 1; // TauntToggle.isOn = card.IsTaunt; } public void OnCardTypeDropDownChanged(int value) { if (currentCardButton == null) { return; } currentCardButton.card.Type = (CardTypes)value; PreviewCard(currentCardButton.card); bagWindow.SetData((CardTypes)value); } public void OnCardClassDropDownChanged(int value) { if (currentCardButton == null) { return; } currentCardButton.card.CardClass = (CardClassTypes)(value - 1); PreviewCard(currentCardButton.card); } #region 按钮响应事件 public void OnBackButtonPressed() { SceneManager.LoadScene("index"); } public void OnSaveButtonPressed() { if (currentCardButton.CheckProperties()) { currentCardButton.card.Save(); } } public void OnSaveGeneratedCardButtonPressed() { generatedCard?.Save(true); } #endregion private void FilterKeyword(BaseCard card) { // BaseCard card = currentCardButton.card; this.GetSystem<IStrapiSystem>().GetFilterSkills(card, (filteredSkills) => { loopScrollView.UpdateScrollViewList(filteredSkills, card.skill); bool isKeywordVaild = filteredSkills.Exists(keyword => keyword.EffectDesc == card.Description); if (!isKeywordVaild) { card.effects?.Clear(); card.Description = ""; } }, () => {} ); } public void OnTauntToggle(bool isTaunt){ if (currentCardButton == null) { return; } // currentCardButton.card.IsTaunt = isTaunt; // currentCardDisplayer.SetCardData(currentCardButton.card); } public IArchitecture GetArchitecture() { return VientianeCard.Interface; }} 能不能帮我优化下代码?
- Assistant
虽然此代码已经实现了一个功能完整的卡片编辑器场景,仍有许多可以改进的地方,以增强代码的清晰性、维护性和扩展性。以下是一些建议:
-
移除无用的代码和注释: 清理代码中不再使用的变量和方法,以及注释掉的代码行可以提高代码清晰度。
-
代码分隔: 这个类很长,包含了许多不同的功能。考虑将其拆分成几个更小的类或系统,分别处理卡牌创建、UI事件、数据保存等等。
-
代码重复: 减少代码重复通过创建额外的方法来统一通用的操作。例如,
CreateNewCard()和CreateNewCardOnTop()方法看起来非常类似,可以重构为一个带有参数来决定放置位置的方法。 -
优化 Start 方法:
Start()方法内有一系列的方法调用,这些可能可以分类并放置到相关的初始化方法中,以提高代码的可读性。 -
MVC分离: 实现MVC(Model-View-Controller)模式或其他类似模式,以便更好地将界面与逻辑分离。这个类似乎既处理界面(按钮点击等),也处理后台逻辑(卡牌创建等),这可能会导致维护问题。
-
事件处理: 对事件处理进行封装,减少与事件处理相关的冗长代码。例如,创建一些管理器或服务来处理用户输入、更新UI组件或持久化数据。
-
用于常量的配置文件或类: 考虑使用配置文件或单独的类来存储像路径这样的字符串常量,这不仅清理了代码,还使得将来改变这些值更容易。
-
数据验证:
checkProperties验证方法名字小写了第一个字母,应改为 CamelCase 形式(如 CheckProperties),而且验证逻辑应该考虑分离到独立的类或服务。 -
使用
#region来分隔代码块: 若你喜欢使用#region,可以将代码块封装进去,这样在某些IDE中可以帮助你更容易的跳转到关心的部分。 -
异常处理: 增加异常处理来处理可能出现的错误,并给出用户友好的反馈。
-
使用命名一致性: 使用一致的命名约定。例如,私有字段通常以一个下划线开始,而公共字段则不包括下划线。
这些仅仅是一些基础指导点,真正的优化和重构可能需要对具体功能和项目整体架构有更深入的了解。希望这些建议对您的项目有帮助。
-
- User
有没有什么优秀的 unity3d 项目代码 可以用来学习的,我感觉我的写的代码挺乱的
- Assistant
是的,有很多优秀的Unity项目代码可以作为学习的参考。以下是一些建议:
-
Unity Official Samples: 在Unity官方网站上,你可以找到各种示例项目,这些项目覆盖了Unity不同方面的知识,例如2D/3D游戏开发、虚拟现实、AI导航等。
- 官方网址:Unity Learn
-
Unity Asset Store 上的免费资源: Unity Asset Store 提供了一些免费的项目和资源,这些资源通常会包含项目源码,你可以通过研究这些资源了解到优秀的Unity项目架构和编程实践。
- 资源商店网址:Unity Asset Store
-
GitHub 上的开源项目: GitHub 是一个寻找开源Unity项目的好地方。很多开发者会将他们的个人或学习项目开源在这个平台上。
- GitHub搜索链接:GitHub Unity Search
以下是一些在GitHub上受欢迎的Unity开源项目的例子:
-
First-Person Shooter Kit: 一个用于学习如何制作第一人称射击游戏的开源项目。
- GitHub链接:FPSKit
-
2D Platformer Controller: 一个2D平台游戏控制器的完整解决方案,优秀的代码结构和注释。
- GitHub链接:Unity-2D-Platformer-Controller
-
Brackeys' Game Dev Tutorials: 著名Unity教程制作者Brackeys的GitHub存档,含有多个学习项目的代码。
- GitHub链接:Brackeys' GitHub
-
Unity Patterns: Unity Patterns是一个包含Unity设计模式和架构实践的网站,这些内容能让你了解如何编写更为结构化、可维护的代码。
- 官方网址:Unity Patterns
-
Unity开发者社区和论坛: Unity开发者社区、论坛和Discord服务器是获取帮助和学习资源的良好渠道。频道成员通常会分享他们的知识和项目代码。
- Unity论坛:Unity Forum
在研究这些资源时,请注意查看项目的授权协议,尤其是在打算将代码或者概念用于自己的商业项目时。此外,用心阅读这些项目的文档和代码注释,以及理解它们的架构便于学习到好的编程实践。
-
- User
stracms card 有个 cardset 的一对一的关联字段 cardset 有一个name ,在unity3d 客户端应该怎么定义这个cardset
- Assistant
在Unity3D客户端定义Strapi CMS中的一对一关联字段
cardset时,你需要创建一个数据模型来反映Strapi中的数据结构。例如,假设你有两个模型Card和CardSet,你可以这样定义它们:[System.Serializable] public class CardSet { public int id; // 或使用 string 如果 id 类型是字符串 public string name; // ...其他CardSet字段 } [System.Serializable] public class Card { public int id; // 或使用 string 如果 id 类型是字符串 public string title; // 你卡牌的其他字段 public CardSet cardset; // 一对一的关联字段 // ...其他Card字段 }这里,我们用
System.Serializable属性标记这两个类,这样Unity就可以序列化它们,而你就能在Inspector视图中查看和编辑这些对象。通过在Card类中创建一个CardSet类型的字段cardset,我们建立了一对一的关联。当你从Strapi API获取这些数据时,你将得到
Card对象中的一个CardSet对象,它包含有关卡片集的信息,如其名称等。这取决于你的API和怎样调用它,在Unity中处理JSON数据通常使用JsonUtility或第三方解析库如Newtonsoft.Json。以下是一个简单的使用
UnityWebRequest和JsonUtility将JSON数据反序列化为上述对象的例子:using UnityEngine; using UnityEngine.Networking; using System.Collections; public class APIClient : MonoBehaviour { private void Start() { StartCoroutine(GetCardData()); } IEnumerator GetCardData() { string apiUrl = "你的Strapi API URL"; using (UnityWebRequest webRequest = UnityWebRequest.Get(apiUrl)) { yield return webRequest.SendWebRequest(); if (webRequest.result == UnityWebRequest.Result.Success) { string jsonResult = System.Text.Encoding.UTF8.GetString(webRequest.downloadHandler.data); Card card = JsonUtility.FromJson<Card>(jsonResult); // 你现在可以访问card里的cardset对象 Debug.Log("Card Name: " + card.title); Debug.Log("CardSet Name: " + card.cardset.name); } else { Debug.LogError("Error: " + webRequest.error); } } } }请注意将
"你的Strapi API URL"替换为你实际的Strapi API的URL。根据你如何设置Strapi的响应,你可能需要调整上述代码以匹配API返回的确切JSON结构。如果返回的是数组或复杂的嵌套数据,你将需要创建一个包裹类或进行适当的对象映射。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.