GameObject Array, Resources Load, OnCollisionEnter and Material

Here is the code folks:

using UnityEngine;
using System.Collections;

public class LeBrick : MonoBehaviour {
	GameObject[] objMatToCompTo;
	// Use this for initialization
	void Start () {
		objMatToCompTo = Resources.LoadAll("(1)BlockPreFab") as GameObject[];
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void OnCollisionEnter(Collision col)
	{
		if (col.gameObject.name == "Ball")
		{
			Debug.Log("hit");
			switch(gameObject.renderer.material.name)
			{
				case "1":
					Debug.Log("destroyed?");
					Destroy(gameObject);
					break;
				case "2":
					gameObject.renderer.material = objMatToCompTo[0].renderer.material;
					break;
				case "3":
					gameObject.renderer.material = objMatToCompTo[1].renderer.material;
					break;
                                default:
                                        break;
                  }
          }
    }
}

hit! prints, destroyed doesnt…

I worked this a few hours, and still can’t find the problem…

appreciate any help! =]

Didn’t know you can use strings in switch case, or can’t you?

The problem might be related to use rendered.material.name in your switch statement. When you do it, a new material is created (an instance of the material you initially set in your object). So, if you set material “1” in inspector, renderer.material.name will return “1 (Instance)”. You can test it by inserting

print(renderer.material.name);

inside switch, after default.

To correct this, you can change your switch statement to:

switch(gameObject.renderer.sharedMaterial.name)

You can also test for instance names as well:

case "1":
case "1 (Instance)":
    Debug.Log("destroyed?");
    Destroy(gameObject);
    break;

though I would probably go with the first solution. But before actually changing your code, I strongly suggest to read and understand the difference between Renderer.material and Renderer.sharedMaterial.