GetSpriteIndex

From ZDoom Wiki
Jump to navigation Jump to search
Note: This feature is for ZScript only.


Actor

native static int GetSpriteIndex(name sprt)

Usage

Returns a SpriteID for the provided four letters of a sprite name. Can be used to modify the actor's sprite dynamically, by setting the result value to the actor's sprite field.

Error.gif
Warning: GetSpriteIndex can only obtain a valid SpriteID if the sprite in question is loaded into memory, otherwise GZDoom may crash, freeze, or pull a random graphic due to reading null/garbage memory.


For a SpriteID to be cached, it has to appear in some actor's States block. It can be any actor (not necessarily the actor where this function is being called), and that actor doesn't have to be instantiated (spawned), it only needs to be present in the code. For example:

class SpriteCacher : Actor abstract //we can use 'abstract' to make sure it can't be spawned
{
	States {
	// State label, duration and other features of the
	// state sequence are not relevant:
	Cache:
		ZOMB A 0;
		stop;
	}
}

having this somewhere in your ZScript will make sure all sprites beginning with ZOMB are loaded into memory upon startup. Frame letters don't matter: the above example will also load ZOMBB, ZOMBC, etc. if they exist.

If the sprite in question is already defined in another actor you're using, caching it additionally isn't necessary; this method is only needed when the sprite in question is only ever set via GetSpriteIndex and never appears in states directly.

Example

This torch will randomly take an appearance of RedTorch, BlueTorch or GreenTorch. The sprite names are stored in a static array and the sprite is set in PostBeginPlay.

class RandomTallTorch : RedTorch 
{
    static const name torchSprites[] = 
    {
        'TRED',
        'TBLU',
        'TGRN'
    };

    override void PostBeginPlay() 
    {
        super.PostBeginPlay();
        sprite = GetSpriteIndex(torchSprites[random(0, torchSprites.Size()-1)]);
    }

    States 
    {
    Spawn:
        #### ABCD 4 bright;
        loop;
    }
}

This is a variation of the same example that also uses A_AttachLightDef to attach a dynamic light to the torch:

class RandomTallTorchWithALight : RedTorch 
{
    static const name torchSprite[] = 
    {
        'TRED',
        'TBLU',
        'TGRN'
    };
    static const name torchLight[] = 
    {
        'BIGREDTORCH',
        'BIGBLUETORCH',
        'BIGGREENTORCH'
    };
    override void PostBeginPlay() 
    {
        super.PostBeginPlay();
        int i = random(0,2);
        sprite = GetSpriteIndex(torchSprite[i]);
        A_AttachLightDef("0",torchLight[i]);
    }
    States 
    {
    Spawn:
        #### ABCD 4 bright;
        loop;
    }
}