- Home /
How to make ray hitting only game objects with tag from list
Hello, How to make a ray hitting only game objects with one of tags from list and how to create that list.
You could just have a ray hit everything, then check to see if the object has a tag from the list.
Answer by highpockets · Mar 18, 2019 at 10:23 PM
RaycastHit hit;
if(Physics.Raycast(startPos, direction, out hit){
if(hit.transform.tag == “TheTagName”){
//do stuff
}
}
That should do it
If you want to make a list of tags:
List<string> tagList = new List<string>();
tagList.Add(“TagOneName”);
tagList.Add(“TagTwoName”);
Then:
foreach( string t in tagList ){
if(t == “DesiredTagName”){
//do something
}
}
@highpockets if the actions are different a switch would do as well
@dargonknight true, that’s a good point.
switch(hit.collider.tag){
case “TagOneName”:
//do TagOneName action
return true;
case “TagTwoName”:
//do TagTwoName action
return true;
}
**switch ins$$anonymous$$d of foreach. Switch is faster
Hello, i am getting an error:
A switch expression of type `System.Collections.Generic.List' cannot be converted to an integral type, bool, char, string, enum or nullable type
What to do with that? I did a list like you shows and used the switch.
Answer by dan_wipf · Mar 19, 2019 at 11:48 AM
the simplest way is to use System.Linq;
if(myTagList.Contains(ihit.transform.tag)
Edit:
Getting an Array of all current Tags in UnityEditor use this:
var myTagList = UnityEditorInternal.InternalEditorUtility.tags;
Edit 2
using System.Linq;
string myTags[] = new string[]{"tag0","tag1","tag2"};
//raycast stuff
if(myTags.Contains(hit.transform.tag)){
switch(hit.transform.tag){
case "tag0":
// do stuff
break;
case "tag1":
//do stuff
break;
case "tag2":
//do stuff
break;
}
}
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Fall collision force with help of raycast 0 Answers
place a object not in a object 0 Answers