- Home /
Search for a prefab with certain property
I have a bunch of prefabs of gameobjects with same attached class. This class contains an identification property (each prefab has different value of this property). I want to search for prefab with certain value of this property and instantiate it. If I can't do it with prefabs, can I do it (it = get gameobject by property of an attached class) with already instantiated gameobjects? (and if I can is this the way to do it? -> https://docs.microsoft.com/en-us/previous-versions/windows/desktop/wmi_v2/how-to-get-a-specific-instance-of-a-class)
Answer by Nimi142 · Sep 01, 2020 at 10:36 PM
Won't doing:
GameObject prefab; // The prefab you have.
ComponentYouWant component = prefab.GetComponent<ComponentYouWant>(); // The component you want to check
if (component != null && component.valueYouWant == something) Success;
Work? That would take the prefab (with the components and stuff you configured for it on the inspector), and try to get the component you want. If the prefab doesn't have the component, then it will be null. If it does, then the other type of the if statement will come into practice and you'll be able to check if it satisfies your goals.
You can do it as many times you want for as many prefabs and components you want. You can also use the HasComponent<>();
function.
Answer by TomArano_Dimenco · Sep 02, 2020 at 09:24 AM
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
is this what you would need? or are the prefabs not in the scene yet?
^ This would work if the objects are in the scene indeed,
Otherwise you could simply assign the prefabs you need in the inspector.
public GameObject[] prefabs;
// identification can be anything
public GameObject GetPrefab(string identification)
{
foreach (var prefab in prefabs)
{
var comp = prefab.GetComponent<YourScript>();
if (comp.identification == identification) return prefab;
//you could return comp here too
}
return null;
}
Yes! U can assign prefabs to an array through inspector and just look through that array to what u need. u wont have to load resources this way, making it easier.
Thank you, @ShadyProductions !! Took a little bit of brain power on my part and I had to think through the function several times (came close to caving and just asking), but I understand what is happening here now, and this is exactly what I needed. :)
Your answer
Follow this Question
Related Questions
Cannot find 3D Prefab after doing a build. 0 Answers
Instantiate moving prefab 1 Answer
How to check if a component is on an instantiated prefab? 1 Answer
Lobbing a Bomb with Instantiate. 1 Answer
Randomly pick then create prefab 2 Answers