Я работаю над проектом Unity, в котором мне нужно изменить текст на объектах после завершения анимации. Несмотря на мои усилия, похоже, цикл не переходит к следующей итерации правильно, а текст на объектах не обновляется должным образом.
Описание проблемы:
Предполагается, что скрипт обновляет текст на объектах-морковках после каждого вопроса. Однако после завершения анимации текст не обновляется должным образом. Похоже, цикл неправильно переходит к следующей итерации.
Что я пробовал:
Отладка для обеспечения правильного потока логики в сопрограмме nextQuestion.
Проверка состояний аниматора и анимации, чтобы убедиться, что они правильно запускаются и заканчиваются.
Убедимся, что текстовые компоненты правильно указаны и доступны.
Не могли бы вы помочь мне найти проблему, которая мешает циклу перейти к следующей итерации и правильно обновить текст?
Вот соответствующая часть моего скрипта:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Bunny : MonoBehaviour
{
public GameObject carrots;
public float speed; // Movement speed of the object
public float currentYrotation;
public string[] questions, answer_keys; // Array of questions and answer keys
string[] answers;
int number = 0;
public TMP_Text question_display;
void Start()
{
StartCoroutine(nextQuestion());
}
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
// Move left along the Z axis
GetComponent().velocity = new Vector3(0, 0, speed);
transform.rotation = Quaternion.Euler(0, currentYrotation - 20, 0);
}
if (Input.GetKey(KeyCode.RightArrow))
{
// Move right along the Z axis
GetComponent().velocity = new Vector3(0, 0, -speed);
transform.rotation = Quaternion.Euler(0, currentYrotation + 20, 0);
}
if (Input.GetKeyUp(KeyCode.RightArrow) || Input.GetKeyUp(KeyCode.LeftArrow))
{
// Stop movement along the Z axis
GetComponent().velocity = new Vector3(0, 0, 0);
transform.rotation = Quaternion.Euler(0, currentYrotation, 0);
}
}
void OnTriggerEnter(Collider obj)
{
if (obj.name == "carrots")
{
if (obj.transform.GetChild(0).GetComponent().text == answers[0])
{
print("correct");
}
else
{
print("wrong");
}
StartCoroutine(nextQuestion());
}
}
IEnumerator nextQuestion()
{
yield return new WaitForSeconds(0.25f);
number++;
question_display.transform.parent.gameObject.SetActive(true);
question_display.text = questions[number];
carrots.GetComponent().enabled = true;
carrots.GetComponent().Play("carrots");
answers = answer_keys[number].Split('|');
for (int i = 0; i < carrots.transform.childCount; i++)
{
carrots.transform.GetChild(i).GetChild(0).GetComponent().text = "";
}
for (int i = 0; i < carrots.transform.childCount; i++)
{
int index;
do
{
index = (int)Random.Range(0, 2.4f);
} while (carrots.transform.GetChild(index).GetChild(0).GetComponent().text != "");
carrots.transform.GetChild(index).GetChild(0).GetComponent().text = answers;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/785 ... ation-ends
Изменение текста на объектах после завершения анимации ⇐ C#
Место общения программистов C#
-
Anonymous
1716326779
Anonymous
Я работаю над проектом Unity, в котором мне нужно изменить текст на объектах после завершения анимации. Несмотря на мои усилия, похоже, цикл не переходит к следующей итерации правильно, а текст на объектах не обновляется должным образом.
Описание проблемы:
Предполагается, что скрипт обновляет текст на объектах-морковках после каждого вопроса. Однако после завершения анимации текст не обновляется должным образом. Похоже, цикл неправильно переходит к следующей итерации.
Что я пробовал:
Отладка для обеспечения правильного потока логики в сопрограмме nextQuestion.
Проверка состояний аниматора и анимации, чтобы убедиться, что они правильно запускаются и заканчиваются.
Убедимся, что текстовые компоненты правильно указаны и доступны.
Не могли бы вы помочь мне найти проблему, которая мешает циклу перейти к следующей итерации и правильно обновить текст?
Вот соответствующая часть моего скрипта:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Bunny : MonoBehaviour
{
public GameObject carrots;
public float speed; // Movement speed of the object
public float currentYrotation;
public string[] questions, answer_keys; // Array of questions and answer keys
string[] answers;
int number = 0;
public TMP_Text question_display;
void Start()
{
StartCoroutine(nextQuestion());
}
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
// Move left along the Z axis
GetComponent().velocity = new Vector3(0, 0, speed);
transform.rotation = Quaternion.Euler(0, currentYrotation - 20, 0);
}
if (Input.GetKey(KeyCode.RightArrow))
{
// Move right along the Z axis
GetComponent().velocity = new Vector3(0, 0, -speed);
transform.rotation = Quaternion.Euler(0, currentYrotation + 20, 0);
}
if (Input.GetKeyUp(KeyCode.RightArrow) || Input.GetKeyUp(KeyCode.LeftArrow))
{
// Stop movement along the Z axis
GetComponent().velocity = new Vector3(0, 0, 0);
transform.rotation = Quaternion.Euler(0, currentYrotation, 0);
}
}
void OnTriggerEnter(Collider obj)
{
if (obj.name == "carrots")
{
if (obj.transform.GetChild(0).GetComponent().text == answers[0])
{
print("correct");
}
else
{
print("wrong");
}
StartCoroutine(nextQuestion());
}
}
IEnumerator nextQuestion()
{
yield return new WaitForSeconds(0.25f);
number++;
question_display.transform.parent.gameObject.SetActive(true);
question_display.text = questions[number];
carrots.GetComponent().enabled = true;
carrots.GetComponent().Play("carrots");
answers = answer_keys[number].Split('|');
for (int i = 0; i < carrots.transform.childCount; i++)
{
carrots.transform.GetChild(i).GetChild(0).GetComponent().text = "";
}
for (int i = 0; i < carrots.transform.childCount; i++)
{
int index;
do
{
index = (int)Random.Range(0, 2.4f);
} while (carrots.transform.GetChild(index).GetChild(0).GetComponent().text != "");
carrots.transform.GetChild(index).GetChild(0).GetComponent().text = answers[i];
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78514412/changing-text-on-objects-after-animation-ends[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия