- Home /
Code for built-in Find() function?
I've been trying to make my own customized Find() function, and it's not successful at all. Can someone please post the original Find() code or make a function that works exactly like the original? Thanks.
My original code is this, but then it ends up becoming a boolean rather than a gameObject:
static var isitTrue = false;
function ScenarioFind(scenario:String){
for(var childx:Transform in story.GetComponentsInChildren(Transform)){
if(childx.GetComponent(Scene_Setup).scenario == scenario){isitTrue = true;}
else if(childx.GetComponent(Scene_Setup).scenario == scenario){isitTrue = false;}
}
if(isitTrue == true){return true;}
else if(isitTrue == false){return false;}
}
But don't correct that unless if you can help modify it enough to function like the Find() code.
Answer by Bunny83 · Jun 10, 2013 at 12:52 AM
Your problem is that probably not every child has a Scene_Setup script attached. So calling GetComponent might return null if there is no such script on the current object. When accessing the "scenario" variable you will get a null reference exception. Also checking the same expression two times in a row doesn't make much sense as well as using a static variable.
Actually your function can be simplified to this:
function ScenarioFind(scenario:String) : GameObject
{
for(var childx : Scene_Setup in story.GetComponentsInChildren(Scene_Setup)){
if(childx.scenario == scenario)
return childx.gameObject;
return null;
}
Keep in mind that GetComponentsInChildren will only "find" active and enabled components. If you want even disabled objects, change it to:
story.GetComponentsInChildren(Scene_Setup, true)
Yeah, what you did worked, and it turned out I didn't really need it after all. But thank you so much!
Your answer
Follow this Question
Related Questions
How to get the objects inside another object and put them in a array? 1 Answer
Find All FindObjectOfType() 1 Answer
How Expensive is Find function? 3 Answers
transform.find and Instantiate do not return the same type? 1 Answer
Variable Assigning with GameObject.Find("") causing NullReferenceException? 0 Answers