Created
February 24, 2025 21:05
-
-
Save jacopocolo/551d29e0b59d4bc9b05e708d816d8be9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using UnityEngine; | |
public class MaterialGenerator : MonoBehaviour | |
{ | |
public Texture2D imageTexture; // Assign in Inspector | |
private Material generatedMaterial; | |
void Start() | |
{ | |
//Get raw size of image | |
string assetPath = UnityEditor.AssetDatabase.GetAssetPath(imageTexture); | |
byte[] tmpBytes = File.ReadAllBytes(assetPath); | |
imageTexture.LoadImage(tmpBytes); | |
float width = imageTexture.width; | |
float height = imageTexture.height; | |
if (width>height){ | |
float x = (width/height)*gameObject.transform.localScale.x; | |
gameObject.transform.localScale = new Vector3(x, gameObject.transform.localScale.y, gameObject.transform.localScale.z); | |
} else { | |
float z = (height/width)*gameObject.transform.localScale.z; | |
gameObject.transform.localScale = new Vector3(gameObject.transform.localScale.x, gameObject.transform.localScale.y, z); | |
} | |
Shader shader = Shader.Find("Universal Render Pipeline/Lit"); | |
generatedMaterial = new Material(shader) | |
{mainTexture = imageTexture}; | |
Renderer renderer = GetComponent<Renderer>(); | |
renderer.material = generatedMaterial; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment