- Home /
Finding GameObject without using the full name
Hi, I have problem with this one:
GameObject.Find("MyGameObject")
finds only GameObjects with this specific name. I have to find GameObjects with with a name that contains a a fragment of string, for example:
GameObject.Find("Car")
finds Car1, Car2 etc. Any ideas? :)
Answer by robertbu · Apr 23, 2014 at 08:24 AM
If you are not using your tags for anything else, then the easiest solution would be to tag all of your cars with a 'Car' tag. Then you would not need a string search. You could then use GameObject.FindGameObjectsWithTag() to get all the cars. If you really need the substring search, you could use GameObject.FindObjectsOfType() to get a list of all the game objects. Then you could cycle through the list using any string comparison that makes sense to find your objects. Note that both FindGameObjectsWithTag() and FindObjectsOfType() only return active game objects and that FindObjectsOfType() is slow.
As a way of creating a more compact search if you need to cycle through all the game objects, take a look at LinQ:
Tags is the most efficient solution. I was just playing with LinQ with your criteria. Since I use LinQ infrequently, I always have to stumble around a bit, but here is a short script:
#pragma strict
import System.Linq;
function Start() {
var carObjects = GameObject.FindObjectsOfType(GameObject)
.Where (function (g) g.name.Contains("Car"));
for (var car : GameObject in carObjects)
Debug.Log(car.name);
}