유니티

유니티 문자열 자르기

파란색까마귀 2022. 2. 14. 14:33

2016. 5. 21. 12:35

https://blog.naver.com/nagne2011/220715457985

 

대화 내용을 입력하는 효과를 만들기 위해서

문자열을 잘라서 1,12,123,1234 이런식으로 마치 타자를 치듯 출력되도록 하는 코드를 짜보았다.

 

기초적인 문법은 아래와 같다

 

 

1
2
3
4
5
6
7
8
9
10
 
        string str = "abcdefg";
 
        //0번부터 3번까지 문자열을 출력합니다.
        this.GetComponent<UILabel> ().text = str.Substring(0,3);
        //출력내용 : abc
 
        //6번부터 문자열 끝까지 출력합니다.
        this.GetComponent<UILabel> ().text = str.Substring(5);
        //출력내용 : fg
cs

 

 

그리고 코루틴을 사용해서 차례대로 출력되도록 만든다

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    public string str = "";
    //출력할 문자열을 string으로 선언해서 받아온다
    public int strNum = 0;
    //문자열의 처음부터 출력할 꺼다
    public float textSpeed = 1.0f;
    //출력 속도는 1.0f초
 
    void Awake()
    {
        StartCoroutine ("TextFuntion");
        //코루틴을 실행한다
    }
 
    void Update () 
    {
        this.GetComponent<UILabel> ().text = str.Substring(0, strNum);
        //현재 출력할 문자열의 갯수에 맞춰 출력한다
    }
 
    IEnumerator TextFuntion()
    {
        while (strNum < str.Length) //문자열의 길이보다 커지면 출력종료
        {
            strNum++;
            //문자열을 하나씩 늘린다
            yield return new WaitForSeconds (textSpeed);
            //출력 속도에 맞춰 대기한다.
        }
    }
cs

 

728x90