- Home /
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! =]
Answer by YoungDeveloper · Oct 03, 2013 at 08:26 PM
Didn't know you can use strings in switch case, or can't you?
http://msdn.microsoft.com/en-us//library/vstudio/06tc147t.aspx
"In the final example, string input is converted to an integer variable, switchExp, which is used for the switch expression. You also can use the string variable, str, directly. To do that, you would change the case labels to specify string values, as is shown in the following code." <- $$anonymous$$icrosoft quote....
You can use strings in switches. Why wouldn't you be able to?
switch(guys_name)
{
case "John":
break;
case "Doug":
break;
}
This is what im trying to do, with the code above...
Correct question: Why im not able to?
Add a debug message, by this you will know are you even entering the switch.
switch(gameObject.renderer.material.name)
{
Debug.Log("going in switch works");
]
Answer by ArkaneX · Oct 04, 2013 at 05:00 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613115249im_/https://answers.unity.com/themes/thub/images/avi.jpg)