Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 30 31
Archives
Today
Total
관리 메뉴

codingfarm

sprite 변경하기 본문

Unity5/기타

sprite 변경하기

scarecrow1992 2020. 6. 5. 01:04

스크립트를 통해 sprite를 변경하는 방법이다.

 

Sprite Renderer에 있는 Sprite 속성에 원하는 스프라이트를 대입해주면 표시되는 그림이 달라진다.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class SpriteTest : MonoBehaviour
{
    // Start is called before the first frame update
 
    public Sprite[] idle;
    public Sprite[] walk;
    int state;
    float cool_time;
    int sprite_index;
    SpriteRenderer spriteRenderer;
    void Start()    {
        state = 0;
        cool_time = 0;
        sprite_index = 0;
        spriteRenderer = GetComponent<SpriteRenderer>();
    }
 
    // Update is called once per frame
    void Update()    {
        if (Input.GetKey(KeyCode.C))        {
            //키 눌림 확인
            if(state == 1) {
                state = 0;
                cool_time = 0;
                sprite_index = 0;
            }
            cool_time += Time.deltaTime;
            spriteRenderer.sprite = walk[sprite_index];
 
            if (cool_time >= 0.1f) {
                cool_time = 0;
                sprite_index++;
                if(sprite_index > 7) {
                    sprite_index = 0;
                }
            }
        }
        else {
            if(state == 0) {
                state = 1;
                cool_time = 0;
                sprite_index = 0;
            }
 
            cool_time += Time.deltaTime;
            spriteRenderer.sprite = idle[sprite_index];
 
            if (cool_time >= 0.1f) {
                cool_time = 0;
                sprite_index++;
                if (sprite_index > 7) {
                    sprite_index = 0;
                }
            }
        }
    }
}
 
cs

C키를 누르면 걷는애니메이션이, 떼고 있으면 대기 애니메이션이 나오는 코드이다.

0.1초에 한번씩 스프라이트가 전환되면서 애니메이션이 재생된다

어려울것 없으니 차근차근 보면 될 코드이다.

 

'Unity5 > 기타' 카테고리의 다른 글

3. 2d 플랫포머 - 캐릭터 이동  (0) 2020.07.26
코루틴  (0) 2020.06.06
mechanim(2d)  (0) 2020.06.05
Ray와 Raycast충돌  (0) 2020.06.05
오브젝트 이동하기  (0) 2020.06.05
Comments