Facepunch.Steamworks Wiki

Revision Difference

GetClientAvatarUnity#544792

<cat>code.unity</cat>⤶ <title>Getting A Client's Avatar</title>⤶ # Getting the Clients Avatar⤶ Firstly we want to get the client's avatar, you can do this by using the GetLargeAvatarAsync() task. To make it super easy you can put it in a method for use later.⤶ ```⤶ private static async Task<Image?> GetAvatar()⤶ {⤶ try⤶ {⤶ // Get Avatar using await⤶ return await SteamFriends.GetLargeAvatarAsync( SteamClient.SteamId );⤶ }⤶ catch ( Exception e )⤶ {⤶ // If something goes wrong, log it⤶ Debug.Log( e );⤶ return null;⤶ }⤶ }⤶ ```⤶ #Coverting Steamworks.Data.Image into UnityEngine.Texture2D⤶ Now we gotta be able to use that image we just grabbed from Steam and be able to use it in Unity. We have to flip the image in order for it to be in the correct orientation. If we don't do this the avatar will be upside down⤶ For the sake of making the code more readable, we can make the converter into an extension method⤶ ```⤶ public static Texture2D Covert( this Image image )⤶ {⤶ // Create a new Texture2D⤶ var avatar = new Texture2D( (int)image.Width, (int)image.Height, TextureFormat.ARGB32, false );⤶ ⤶ // Set filter type, or else its really blury⤶ avatar.filterMode = FilterMode.Trilinear;⤶ ⤶ // Flip image⤶ for ( int x = 0; x < image.Width; x++ )⤶ {⤶ for ( int y = 0; y < image.Height; y++ )⤶ {⤶ var p = image.GetPixel( x, y );⤶ avatar.SetPixel( x, (int)image.Height - y, new UnityEngine.Color( p.r / 255.0f, p.g / 255.0f, p.b / 255.0f, p.a / 255.0f ) );⤶ }⤶ }⤶ ⤶ avatar.Apply();⤶ return avatar;⤶ }⤶ ```⤶ ⤶ #Result⤶ Now to get the image and cache it you can easily just do⤶ ```⤶ // Get the task⤶ var avatar = GetAvatar();⤶ ⤶ // Use Task.WhenAll, to cache multiple items at the same time⤶ await Task.WhenAll( avatar );⤶ ⤶ // Cache Items⤶ Cache.Avatar = avatar.Result?.Covert();⤶ ```⤶ #Tips⤶ I'd recommend precaching the avatar, Like I had done in the example above.