Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Swapping TMPro Sprite Atlas at runtime

Discussion in 'Editor & General Support' started by rude_rodent, Sep 19, 2023.

  1. rude_rodent

    rude_rodent

    Joined:
    Jun 8, 2021
    Posts:
    2
    Hi! My game has the option to use mouse & keyboard or controller interchangeably. I have a TextMesh Pro sprite asset containing the game's controller layout that is used by a lot of TMPro text objects.

    I need to be able to swap the controller sprite asset at runtime to the mouse & keyboard version and have it update in all of my text objects. As far as I can tell, I can do this by either a) replacing the sprite atlas texture in the sprite asset prefab, or b) replacing the default sprite asset (in TMPro settings) with a mouse & keyboard sprite asset prefab. Option A works in editor no problem, but when the texture is swapped at runtime it doesn't update my text objects -- is there some kind of refresh function I need to call for this to work? As for option B, it seems that the default sprite asset is read only, so unless I'm missing something I don't think I can swap it out.

    The only workaround I have for this is finding all text objects in update and manually switching their sprite assets out individually, which is causing an amount of lag on lower-end PCs running the game. If anyone has any suggestions, I'd appreciate it very much!
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    I've just done this by having a component on each game object that has an image that needs to be updated. Said component just hooks into whatever overarching system you use to detect when the type of input has changed, and changes the Image Component's sprite with the new image.

    I usually detect when the input device changes using the InputSystem.onEvent delegate and using that to tell when the input comes from a different device. Then you broadcast that change with a global event so anything that cares about it can update as needed.
     
    rude_rodent likes this.
  3. rude_rodent

    rude_rodent

    Joined:
    Jun 8, 2021
    Posts:
    2
    Thanks so much! This is a great solution!
     
    spiney199 likes this.