1
\$\begingroup\$

I have a Typewriter script attached to the text, which is a child of a button.
I want this script to run only if the button is interactable.

I made a public variable to store the button and used GetComponent() method, but it doesn't work.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

// attach to UI Text component (with the full text already there)

public class UITextTypeWriter : MonoBehaviour {


public Text txt;
string story;
public Button ParrentButton;

void Awake()
{
    txt = GetComponent<Text>();
    story = txt.text;
    txt.text = "";

        Button b = ParrentButton.GetComponent<Button>();
        if (b.interactable)
        {
            StartCoroutine("PlayText");
        }       
}

IEnumerator PlayText()
{
    foreach (char c in story)
    {
        txt.text += c;
        yield return new WaitForSeconds(0.125f);
    }
}

}

Where is my mistake? I would be grateful for your help!

Thank you in advance!

\$\endgroup\$
1
\$\begingroup\$

The check is only made once: When this script first awakens it checks to see if the button is enabled, if it is, the entire typewriter effect will occur. If the button is not enabled, then the typewriter effect will never occur (unless the script itself is disabled and re-enabled).

If you want to wait for the button to become enabled, you need to use the Update() method. If you want to stop the typewriter effect after it starts, you'd have to restructure your code entirely.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UITextTypeWriter : MonoBehaviour {

    public Text txt;
    private string story;
    public Button ParrentButton;
    private bool writing;

    void Awake()
    {
        txt = GetComponent<Text>();
        story = txt.text;
        txt.text = "";
        writing = false;
    }

    private void Update()
    {
        if (!writing)
        {
            Button b = ParrentButton.GetComponent<Button>();
            if (b.interactable)
            {
                writing = true;
                StartCoroutine("PlayText");
            }
        }
    }

    IEnumerator PlayText()
    {
        foreach (char c in story)
        {
            txt.text += c;
            yield return new WaitForSeconds(0.125f);
        }
    }
}

The writing boolean is so we don't check the button again after we've started (or the coroutine would run more often than we want).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.