Hello, I was learning how to make a choose your own story game, and wanted to create a typewriter effect for the dialog. I found some code online, that, I believe would have worked if it weren’t for the fact that the course work redirected the text within the inspector to a different script called “states” so that when the player chose a state, the text would then change and be sent to the text spot. I tried to implement it myself and got coroutine errors. I haven’t learned about coroutines and ienumerators yet so I have no idea how to fix this. Anyway, here’s the code I found online:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TypeWriterEffect : MonoBehaviour
{
public float delay = 0.1f;
public string fullText;
private string currentText = "";
void Start()
{
StartCoroutine(ShowText());
}
IEnumerator ShowText()
{
for(int index = 0; index <= fullText.Length; index++)
{
currentText = fullText.Substring(0,index);
yield return new WaitForSeconds(delay);
}
}
}
Here is the original State script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject
{
[TextArea(10,14)] [SerializeField] string storyText;
[TextArea(2,5)] [SerializeField] string choice1;
[TextArea(2,5)] [SerializeField] string choice2;
[TextArea(2,5)] [SerializeField] string choice3;
[SerializeField] State[] nextStates;
public State[] GetNextStates()
{
return nextStates;
}
public string GetStoryState()
{
return storyText;
}
public string GetChoice1()
{
return choice1;
}
public string GetChoice2()
{
return choice2;
}
public string GetChoice3()
{
return choice3;
}
}
and how I attempted to change it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject
{
[TextArea(10,14)] [SerializeField] string storyText;
[TextArea(2,5)] [SerializeField] string choice1;
[TextArea(2,5)] [SerializeField] string choice2;
[TextArea(2,5)] [SerializeField] string choice3;
[SerializeField] State[] nextStates;
private string currentText = "";
[SerializeField] float delay;
public State[] GetNextStates()
{
return nextStates;
}
public string GetStoryState()
{
StartCoroutine(ShowText());
}
public string GetChoice1()
{
return choice1;
}
public string GetChoice2()
{
return choice2;
}
public string GetChoice3()
{
return choice3;
}
IEnumerator ShowText()
{
for(int index = 0; index <= storyText.Length; index++)
{
currentText = storyText.Substring(0,index);
yield return new WaitForSeconds(delay);
}
}
}