- Home /
The question is answered, right answer was accepted
Unity string comparison not working...
I cant seem to get the name of the object (string) to match the string variable Roid1, in the IF statement. The name of the selected target is Roid1 when selected in game.
public Transform selectedTarget;
private string Roid1;
private string Roid2;
if(selectedTarget.name == Roid1){
Material roidselected = Resources.Load("RoidSelected1", typeof(Material)) as Material;
selectedTarget.renderer.material = roidselected;
}
if(selectedTarget.name == Roid2){
Material roidselected2 = Resources.Load("RoidSelected2", typeof(Material)) as Material;
selectedTarget.renderer.material = roidselected2;
}
No i didnt. Unless im misunderstanding, the reason i didnt, was so that selectedTarget.name could be compared in following IF statements and thus set different materials accordingly.
It's fine :D
You understand now and that is the important thing ;)
Answer by MrSoad · Dec 15, 2014 at 04:50 PM
Have you given the string "Roid1" a value(string) before this if statement, such as :
Roid1 = "The_Name_Of_The_Target_You_Want";
Then you are comparing whatever the value(string) of this "selectedTarget.name" is to nothing, "Roid1" has no value so it will never == "selectedTarget.name".
In an If statement the condition has to be met for it to execute. In your case the two sides selectedTarget.name and Roid1 have to match exactly. How can something with no value match anything other than something else that has no value. You are misunderstanding how this code works. You must have several possible names that can be the "selectedTarget.name" so you need to check against each name :
if(selectedTarget.name == "Name_Of_Your_First_Object") {
$$anonymous$$aterial roidselected = Resources.Load("RoidSelected1", typeof($$anonymous$$aterial)) as $$anonymous$$aterial;
selectedTarget.renderer.material = roidselected;
}
if(selectedTarget.name == "Name_Of_Your_Second_Object") {
$$anonymous$$aterial roidselected2 = Resources.Load("RoidSelected2", typeof($$anonymous$$aterial)) as $$anonymous$$aterial;
selectedTarget.renderer.material = roidselected2;
}
You don't even need the string vars for this. Hope this makes it clearer :)
Thanks @meat5000, I was making a right mess of trying to sort the order out :)