你好,这是问题所在。我有一个包含精灵的数组,我需要在 UI 画布中迭代和显示精灵,我不明白为什么 Unity 会这样抱怨:
大批:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[CreateAssetMenu(menuName ="Dialogue/DialogueObject")]
public class DialogueObject : ScriptableObject
{
[SerializeField] [TextArea] private string nameChar;
[SerializeField] private Sprite[] imgObj;
[SerializeField] [TextArea] private string[] dialogue;
[SerializeField] private Response[] responses;
public Sprite[] ImgObj => imgObj;
public string NameChar => nameChar;
public string[] Dialogue => dialogue;
public bool HasResponses => Responses != null && Responses.Length > 0;
public Response[] Responses => responses;
}
这是我尝试显示图像的代码:
using UnityEngine;
using TMPro;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class DialogueUI : MonoBehaviour
{
[SerializeField] private GameObject dialogueBox;
[SerializeField] private TMP_Text textLable;
[SerializeField] private TMP_Text textName;
[SerializeField] private Image imgHandler;
public bool IsOpen {get; private set;}
private ResponseHandler responseHandler;
private TypeWriterEffect typeWriterEffect;
private void Start() {
typeWriterEffect=GetComponent<TypeWriterEffect>();
responseHandler = GetComponent<ResponseHandler>();
imgHandler = GetComponent<Image>();
CloseDialogueBox();
}
public void ShowDialogue(DialogueObject dialogueObject){
IsOpen = true;
dialogueBox.SetActive(true);
string nameChar = dialogueObject.NameChar;
textName.text = nameChar;
StartCoroutine(StepTroughtDialogue(dialogueObject));
StartCoroutine (ImgInDialogue(dialogueObject));
}
public void AddResponseEvents(ResponseEvent[] responseEvents){
responseHandler.AddResponseEvents(responseEvents);
}
private IEnumerator ImgInDialogue(DialogueObject dialogueObject){
for (int i = 0; i < dialogueObject.ImgObj.Length; i++ ){
Sprite imgObj = dialogueObject.ImgObj[i];
imgHandler.sprite = imgObj;
yield return null;
yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Space));
}
}
private IEnumerator StepTroughtDialogue(DialogueObject dialogueObject){
for (int i = 0; i < dialogueObject.Dialogue.Length; i++ ){
string dialogue = dialogueObject.Dialogue[i];
yield return RunTypingEffect(dialogue);
textLable.text = dialogue;
if (i == dialogueObject.Dialogue.Length - 1 && dialogueObject.HasResponses) break;
yield return null;
yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Space));
}
if (dialogueObject.HasResponses)
{
responseHandler.ShowResponses(dialogueObject.Responses);
}
else
{
CloseDialogueBox();
}
}
private IEnumerator RunTypingEffect(string dialogue){
typeWriterEffect.Run(dialogue, textLable);
while (typeWriterEffect.IsRunning){
yield return null;
if (Input.GetKeyDown(KeyCode.Space)){
typeWriterEffect.Stop();
}
}
}
public void CloseDialogueBox(){
IsOpen = false;
dialogueBox.SetActive(false);
textName.text=string.Empty;
textLable.text=string.Empty;
}
}