I am making a falling block game. The blocks can be red, orange, yellow, green, or blue. Besides just having different materials, each color has other properties I'll need to implement later.
I also want it to be possible for other objects to change the color of each individual instance of Box later on. I'm not sure if this is formed correctly, but I don't get any errors with this code:
public class BoxProperties : MonoBehaviour {
public Material RedMat;
public Material OrangeMat;
public Material YellowMat;
public Material GreenMat;
public Material BlueMat;
public enum BoxType { Red, Orange, Yellow, Green, Blue }
public BoxType myType;
////snipped Start() and Update()
public void setType(BoxType newtype) {
switch (newtype) {
case BoxType.Red:
renderer.material = RedMat;
break;
case BoxType.Orange:
renderer.material = OrangeMat;
break;
case BoxType.Yellow:
renderer.material = YellowMat;
break;
case BoxType.Green:
renderer.material = GreenMat;
break;
case BoxType.Blue:
renderer.material = BlueMat;
break;
}
myType = newtype;
}
}
I made setType() public so other objects can use it to change the type of any given instance.
Additionally, I have a non-renderable cube that represents a spawn volume. I am able to get the Box instances to spawn at random points in the cube and fall, but I am not sure how I can get at the prefab instance's setType method to set the type of box after spawning.
public class SpawnBoxes : MonoBehaviour {
private Vector3 nextpos; //Randomly picked new spawn position
private float collecttime; //Counts how long has passed since the last spawn
private GameObject nextbox;
public float spawntime;
public GameObject spawnee; //Box object goes here
// Use this for initialization
void Start () {
collecttime = 0;
}
// Update is called once per frame
void Update () {
collecttime += Time.deltaTime;
if (collecttime > spawntime) {
nextpos = randPos(renderer.bounds.size, transform.position);
collecttime = 0;
nextbox = Instantiate(spawnee,nextpos,Random.rotation) as GameObject;
//Set type of nextbox, not sure how to access that function, but it's part of a component script attached to the Box prefab
nextbox.GetComponent("BoxProperties").setType(BoxType.Green); //Doesn't work.
}
}
//snipped randPos()
}
I realize there are some other approaches, like making separate prefabs for each Box type and spawning one randomly, but I wonder if there is a way to make this call work?
↧