Read Texture Data from C# Scripts




Published: 25 Oct 2022

In this Unity tutorial you'll learn how to sample texture data from within your C# scripts and do something based on the sampled result. Specifically today we'll be using the grayscale value of the colors to choose a weighted random pixel. Once we know that we'll be updating a virtual texture on a SpriteRenderer to show us the bounds of where we were sampling and the specific pixel sampled each time.


Reading texture data in your scripts has a wide variety of applications in Unity. From Editor Scripting to show brushes, to runtime weighted bullet spread there's as many options as you can come up with!


๐Ÿ‘จโ€๐Ÿ’ปAs always, all code from this video is available on GitHub: https://github.com/llamacademy/read-texture-data


๐Ÿท๏ธSave 25% on the ultimate C# IDE: JetBrains Rider with code LLAMACADEMY: https://www.jetbrains.com/store/?section=personal&billing=yearly


๐Ÿ“š Resources

โšซ Get Pixels: https://docs.unity3d.com/ScriptReference/Texture2D.GetPixels.html

โšซ Get Raw Texture Data: https://docs.unity3d.com/ScriptReference/Texture2D.GetRawTextureData.html

โšซ Create Sprite: https://docs.unity3d.com/ScriptReference/Sprite.Create.html

โšซ Create Texture2D: https://docs.unity3d.com/ScriptReference/Texture2D-ctor.html


๐Ÿงก Believe in LlamAcademy's mission and have received value from the videos? Here's how you can show your support:

๐ŸŒŸ Patreon: https://www.patreon.com/llamacademy

๐ŸŒŸ YouTube Member: https://www.youtube.com/channel/UCnWm6pMD38R1E2vCAByGb6w/join or click the Join button on any video

๐Ÿ“š Take my Unity ShaderGraph Course:

https://www.gamedev.tv/p/unity-shader-graph?affcode=45216_kuvg0bp7

๐Ÿ‘• Get yourself some LlamAcademy merch: https://llamacademy.myspreadshop.com/

๐Ÿ’ธ Use my Affiliate Link for Humble Bundles https://humblebundleinc.sjv.io/9g4ak4

๐Ÿ’ธ Publisher Sale! 50% OFF an entire publisher's Assets! Publisher changes weekly! https://assetstore.unity.com/publisher-sale?aid=1101l9QvC (affiliate)

๐Ÿ’ธ Save up to 50% on NEW Assets: https://assetstore.unity.com/?new_sale=true&orderBy=1&aid=1101l9QvC (affiliate)


Some links may be affiliate links, which at no additional cost to you, gives me a small portion of the purchase.


Connect on Social Media

Some links may be affiliate links, which at no additional cost to you, gives LlamAcademy a small portion of the purchase.