Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Tags
more
Archives
Today
Total
관리 메뉴

mooni

[Unity] 3차 Study : SwitchAction Script 본문

Unity

[Unity] 3차 Study : SwitchAction Script

mooni_ 2024. 3. 12. 13:34

[SwitchAction]

변수 선언부

public GameObject targetMoveBlock;    //스위치와 연결할 오브젝트 받을 변수
public Sprite imageOn;    //스위치 켜진 이미지
public Sprite imageOff;    //스위치 꺼진 이미지
public bool on = false;    //스위치 온오프 여부

 

 


Start()

void Start()
{
    if(on)    //스위치 On | Off 상태에 따라 이미지 변환
    {
        GetComponent<SpriteRenderer>().sprite = imageOn;
    }
    else
    {
        GetComponent<SpriteRenderer>().sprite = imageOff;
    }
    
}

 

 


OnTriggerEnter2D(Collider2D col)

void OnTriggerEnter2D(Collider2D col)
{
    if(col.gameObject.tag == "Player")    //접촉 대상이 Player이면 아래 기능 실행
    {
        if (on)    //스위치 on
        {
            on = false;    //스위치 off
            GetComponent<SpriteRenderer>().sprite = imageOff;    //이미지 변환
            MovingBlock movBlock = targetMoveBlock.GetComponent<MovingBlock>();
            //연결된 블록 오브젝트의 MovingBlock Script를 가져옴
            movBlock.Stop();    //Stop()함수 실행 : isCanMove = false;
        }
        else
        {
            on = true;    //스위치 on, 이미지 변환
            GetComponent<SpriteRenderer>().sprite = imageOn;
            MovingBlock movBlock = targetMoveBlock.GetComponent<MovingBlock>();
            movBlock.Move();    //Move()함수 실행 : isCanMove = true;
        }
    }   
}

 

 

 

*교재 : 누구나 할 수 있는 유니티 2D 게임 제작