Multiple sprite, get components by script.

 GameObject _gameObject = new GameObject(_name);   
            _gameObject.AddComponent<SpriteRenderer>();
            _gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(sprName);

If sprite mode is single, everything works well. _name is name of sprite.
If sprite mode is multiple, I can not get the components of the sprite.

As I recall, when you have a sprite sheet (multiple-mode sprite texture) in a resources folder, you have to use Resources.LoadAll, and then iterate over the results to find the particular sprite you want.

1 Like
 GameObject _gameObject1 = new GameObject("test");
            _gameObject1.AddComponent<SpriteRenderer>();
            _gameObject1.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Stars");
            _gameObject1.GetComponent<Transform>().position = new Vector2(0, 0);
            Sprite[] _sprite = (Sprite[])Resources.LoadAll("Stars");           
            _gameObject1.GetComponent<SpriteRenderer>().sprite = _sprite[2];

draws _sprite as single mode

Sprite[ ] _sprite = (Sprite[ ])Resources.LoadAll(“Stars”); →
InvalidCastException: Cannot cast from source type to destination type.

Try using the generic form…

Sprite[] sprites = Resources.LoadAll<Sprite>("Stars");
3 Likes

Thanks. It works.

GameObject _gameObject1 = new GameObject("test");
            _gameObject1.AddComponent<SpriteRenderer>();           
            _gameObject1.GetComponent<Transform>().position = new Vector2(0, 0);
            Sprite[] _sprite = Resources.LoadAll<Sprite>("Stars");
            _gameObject1.GetComponent<SpriteRenderer>().sprite = _sprite[2];
1 Like