Reputation: 33
I'm am trying to create a script that continuously generates objects and attaches a script to all the generated objects. I want the attached script to after 3 seconds, change the material on the object and add a box collider. My problem is with the material. Since the object was randomly generated, I don't know how to set the material variable. This is my 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 ();
}
}
And this is the script that gets attached:
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;
}
}
Upvotes: 3
Views: 5845
Reputation: 877
You can make a public static int like this. Your Spawner:
public Material mat;
public static Material mat2;
void Start(){
mat2 = mat;
}
And in your astroid script:
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;
}
}
Upvotes: 1
Reputation: 1199
You could just load it from resources
mat = Resources.Load("myMaterial.mat", typeof(Material)) as Material;
Upvotes: 0