- Home /
Changing sprite properties at runtime
Hi,
I have the following code:
public void OnTriggerEnter(Collider c)
{
Debug.Log("Rescued wench");
MeshRenderer mesh = gameObject.GetComponent<MeshRenderer>();
mesh.material = wench_rescued;
Sprite sprite = gameObject.GetComponent<Sprite>();
sprite.width = 70;
sprite.height = 106;
sprite.pixelDimensions.x = 63;
sprite.pixelDimensions.y = 128;
sprite.lowerLeftPixel.y = 128;
Debug.Log(gameObject.GetComponent<Sprite>().width);
}
The change of material works. However, the width and height of the sprite does not change. Curiously, the values are actually changing (as you can see I'm logging the width after the change), but there is no visual change. Any ideas why? Do I have to change the scale of the transform? This would be a pain working out the exact scale to make it look right.
Update: I just ran into this problem again with another object. With this one I don't want to change the width and height of the sprite, just the pixel dimensions and lower left pixel, because its using a different sprite sheet for another animation.
public void OnTriggerEnter(Collider c)
{
Debug.Log("Collided!");
Moonshine moonshine = c.GetComponent<Moonshine>();
if (moonshine != null)
{
MeshRenderer mesh = GetComponent<MeshRenderer>();
mesh.material = drinking;
mySprite.PlayAnim(1);
Sprite sprite = GetComponent<Sprite>();
sprite.pixelDimensions.x = 512;
sprite.pixelDimensions.y = 512;
sprite.lowerLeftPixel.y = 512;
}
}
Once again, the material is being changed successfully, but the sprite dimensions are not changing, even though the values are actually being changed there is no difference on screen. It doesn't matter what I change them to, nothing changes visually. Can anyone help with this? I am using normal Sprites (not packed sprites) in SM2.
Answer by disband85 · Dec 14, 2010 at 12:22 AM
I managed to get around this problem by splitting up my sprite sheets into separate images for each frame, then using the Packed Sprite and Super Sprite instead of the normal Sprite.
Answer by speedb · Jan 23, 2011 at 01:30 PM
instead of
sprite.pixelDimensions.x = 63; sprite.pixelDimensions.y = 128; sprite.lowerLeftPixel.y = 128;
do
sprite.SetPixelDimensions(new Vector2(63f,128f));
same for lowerLeftPixel:
sprite.SetLowerLeftPixel(new Vector2(....));