2013年7月30日 星期二

[Unity] Assign Texture and Material (Editor Script)

複製已存在材質並該改貼圖後賦予至模型

// create material
Material newMaterial = new Material( Shader.Find("Diffuse"));
// assign shader
newMaterial.shader = sourceMaterial.shader;
// copy properties from existing material
newMaterial.CopyPropertiesFromMaterial(sourceMaterial);
// create texture from asset(asset path)
Texture texture = (Texture)AssetDatabase.LoadAssetAtPath( textureRelativePath, typeof(Texture));
// assign texture to material
newMaterial.SetTexture("_MainTex", texture);
// create material asset
AssetDatabase.CreateAsset(newMaterial, newMaterialAssetRelativePath);
// assign material to gameObject
AssignMaterial( gameObject, newMaterial );

在建立texture時需注意,在editor部份可以使用AssetDatabase.LoadAssetAtPath,而runtime則需使用Resource.Load

沒有留言:

張貼留言