实现效果:可以实时生成材质和物体。并且每个材质的颜色不一样。材质生成之后会从在指定文件夹。
直接上代码,大家可以把代码复制黏贴使用,用了之后就知道了:
using UnityEngine;
using System.Collections;
using UnityEditor;
public class GenterMaterial : MonoBehaviour {
public int maxNumber;
public Material addMaterial;
Texture2D texture = null;
float X;
float Y;
float Z;
float colorR;
float colorG;
float colorB;
float number;
public Color color;
public int colorChange;
public float timeInterval = 0.5f;
private float m_Time = 0;
// Use this for initialization
void Start ()
{
texture = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/imgs/Displacement2.jpg", typeof(Texture2D));
AssetDatabase.DeleteAsset("Assets/metial");
AssetDatabase.CreateFolder("Assets", "metial");
X = this.transform.position.x;
Y = this.transform.position.y;
Z = this.transform.position.z;
colorR = color.r;
colorG = color.g;
colorB = color.b;
number = (float)colorChange / (maxNumber - 1);
}
public int meshNumber = 0;
// Update is called once per frame
void Update () {
m_Time += Time.deltaTime;
if (m_Time > timeInterval && meshNumber < maxNumber) {
meshNumber++;
GenterBule();
m_Time = 0;
}
}
float posOffset;
void GenterBule() {
if (colorR <= 1) {
colorR += number;
}
if (colorG <= 1) {
colorG += number;
}
if (colorB <= 1) {
colorB += number;
}
Material mat;
if (addMaterial == null) {
mat = new Material(Shader.Find("Transparent/Diffuse"));
mat.mainTexture = texture;
posOffset = 1;
} else {
mat = new Material(addMaterial);
posOffset = 2;
}
mat.color = new Color(colorR, colorG, colorB, 1);
AssetDatabase.CreateAsset(mat, "Assets/metial/MyMaterial" + meshNumber + ".mat");
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.parent = this.transform;
sphere.GetComponent<MeshRenderer>().material = mat;
sphere.transform.position = new Vector3(X, Y, Z);
X += posOffset;
if (X >= 10) {
Y += posOffset;
X = this.transform.position.x;
}
}
}