모래 조각 유닛에서 코드로sprite 만들기

2000 단어 모래 조각 유닛
string sprite_path = "img/   ";    //Application.dataPath + 
        Debug.Log(sprite_path);
        Texture2D texture = Resources.Load(sprite_path) as Texture2D;
        SpriteRenderer spriteRenderer = transform.GetComponent();
        Debug.Log("texture size:"+texture.width.ToString() + "\t" + texture.height.ToString());
        spriteRenderer.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);

주의해야 할 점:
1. Resources를 사용합니다.Load 에서 읽은 리소스 파일은 Assets 아래의 Resources 폴더에 있어야 합니다.
2. 자원 파일은 접미사 이름을 쓰지 마세요!
여러 sprite를 만드는 예:
//  attach camera ,          
    void create_sprites()
    {
        transform.GetComponent().orthographicSize = (float)Screen.height / 2 / 100;
        string sprite_path = "img/   ";
        Texture2D texture = Resources.Load(sprite_path) as Texture2D;
        Debug.Log("texture size:" + texture.width.ToString() + "," + texture.height.ToString());
        int offset = 0;
        for (int k = 0; k < 2; k++)
        {
            GameObject new_empty = new GameObject();
            new_empty.AddComponent();
            SpriteRenderer spr = new_empty.GetComponent();
            //  ,     ,           
            spr.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
            //    GameObject   (  ,  ,  )
            //         。x     ,y     
            Vector3 vec = transform.GetComponent().ScreenToWorldPoint(new Vector3(offset, 0, 10));
            new_empty.GetComponent().position = vec;
            offset += texture.width;
            
        }
        
    }

참고:
sprite의 실제 크기는 예상된 픽셀 크기와 다를 수 있습니다.이것은 카메라의 사이즈 설정이 잘못되어 발생한 것이다.화면 높이에 따라 계산해야 합니다. 여기서 100은 기본pixels to units 단위입니다.

좋은 웹페이지 즐겨찾기