How do I change a Sprite's textureRect at runtime?

Hi!

I’m using Unity 4.6, and I’ve made a sprite like this:

    AtlasFrameData frame = _testAtlas.GetFrameByIndex(0);
    Rect spriteRect = new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y);
    Sprite _theSprite = Sprite.Create(_testAtlas.AtlasTexture, spriteRect, new Vector2(0, 0));

The texture is an atlas, and I have a bunch of data read in from an XML file telling me where the frames are. I want to do this in Update():

    AtlasFrameData frame = _testAtlas.GetFrameByIndex(_currentFrame);
    Rect spriteRect = new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y);
    _theSprite.textureRect = spriteRect;

But I’m unable to do this since .textureRect is readonly. I could create a new Sprite each frame, but I suspect this is not going to perform well with tons of Sprites.

Got it. You create all the Sprites up front and keep them. Each Sprite object takes about 500 bytes of RAM, and you just set the Image.Sprite attribute to the frame you want.

Sprite[] _animationFrameSprites;
private Image _theImage;
private GameObject _theObj;
private Vector3 _theRootPosition;

void Start()
{
    AtlasFrameData frame;
    for (int i = 0; i < _testAtlas.NumberOfFrames; i++)
    {
        frame = _testAtlas.GetFrameByIndex(i);
        Rect spriteRect = new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y);
        _animationFrameSprites *= Sprite.Create(_testAtlas.AtlasTexture, spriteRect, new Vector2(0, 0));*

}
}
void Update()
{
_currentFrame++;
if (_currentFrame >= _testAtlas.NumberOfFrames)
{
_currentFrame = 0;
}
AtlasFrameData frame = _testAtlas.GetFrameByIndex(_currentFrame);
_theObj.transform.position = _theRootPosition + new Vector3(frame.Offset.x, frame.Offset.y, 0);
_theImage.sprite = _animationFrameSprites[_currentFrame];
_theImage.SetNativeSize();
}