[英]Unity - Add Material To Game Object
我正在嘗試創建一個腳本,該腳本連續生成對象並將腳本附加到所有生成的對象。 我希望附加的腳本在3秒后,更改對象上的材質並添加一個盒子對撞機。 我的問題是材料。 由於對象是隨機生成的,因此我不知道如何設置材質變量。 這是我的Spawner:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
//Variables
public float x_max;
public float x_min;
public float y_max;
public float y_min;
private float Size;
public float s_max;
public float s_min;
public float w_max;
public float w_min;
private float ProceduralCacheSize;
private GameObject sphere;
private float waitTime = 5f;
private int fix;
// Use this for initialization
void Start () {
Spawn ();
Spawn ();
Spawn ();
StartCoroutine("MyCoroutine");
}
// Update is called once per frame
void Update () {
}
void Spawn(){
Size = Random.Range (s_min, s_max);
sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
sphere.transform.position = new Vector3 (Random.Range (x_min, x_max), Random.Range (y_min, y_max), 0);
sphere.transform.localScale = new Vector3 (Size, Size, Size);
var fbs = sphere.AddComponent<Astroid> ();
}
IEnumerator MyCoroutine(){
StartCoroutine("Change");
waitTime = Random.Range (w_min, w_max);
yield return new WaitForSeconds(waitTime);
StartCoroutine("MyCoroutine");
StartCoroutine("Change");
Spawn ();
}
}
這是附帶的腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Astroid : MonoBehaviour {
//I need to be able to set this variable to a material
public Material mat;
// Use this for initialization
void Start () {
this.GetComponent<SphereCollider>().enabled = false;
StartCoroutine("Change");
}
// Update is called once per frame
void Update () {
}
IEnumerator Change(){
yield return new WaitForSeconds (3);
this.GetComponent<SphereCollider>().enabled = true;
this.GetComponent<Renderer> ().material = mat;
}
}
您可以從資源中加載它
mat = Resources.Load(“ myMaterial.mat”,typeof(Material))作為Material;
您可以像這樣使public static int。 您的Spanner:
public Material mat; public static Material mat2; void Start(){ mat2 = mat; }
在您的astroid腳本中:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Astroid : MonoBehaviour { //I need to be able to set this variable to a material //public Material mat; // Use this for initialization void Start () { this.GetComponent<SphereCollider>().enabled = false; StartCoroutine("Change"); } // Update is called once per frame void Update () { } IEnumerator Change(){ yield return new WaitForSeconds (3); this.GetComponent<SphereCollider>().enabled = true; this.GetComponent<Renderer> ().material = Spawner.mat2; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.