Game !







Unity UI 에서 Image 객체를 찾고,

스크립트 내에서 Image의 Sprite 교체하는 방법





Canvas - Panel - Image 사용한다고 가정합니다.




1. 스크립트 내에서 Image 변수에 컴포넌트를 할당하고 싶을 경우,



- Image 에 userTag1 태그가 되어있다고 가정합니다




1
2
3
4
5
6
7
8
9
10
11
public class A : MonoBehaviour
{
    public GameObject imageObj;
    public Image myImage;
 
    Start()
    {
        imageObj = GameObject.FindGameObjectWithTag("userTag1");
        myImage = imageObj.GetComponent<Image>();
    }
}
cs







2. 스크립트 내에서  Image 그림을 바꾸고 싶을 경우,









Image 안의 Image(Script) 부분 컴포넌트입니다.


그림을 바꿔주고 싶을 때 Source Image 부분을 바꿔줘야하는데,


.png 이미지는 Sprite(2D and UI) 로 설정해두었습니다.




위의 코드에서 추가하였습니다.




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 class A : MonoBehaviour
{
    public GameObject imageObj;
    public Image myImage;
 
    Start()
    {
        imageObj = GameObject.FindGameObjectWithTag("userTag1");
        myImage = imageObj.GetComponent<Image>();
    }
 
 
 
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Func();
        }
    }
 
 
    void Func()
    {
        mySkimyImage.sprite = 
                        Resources.Load<Sprite>("SkillIcons/Sword_Skill"
                        as Sprite;
    }
}
cs