C# find objects of type and store them in a array
Hi!
I been trying to figure this out for a very long time now without any real success. Similar questions have been asked which inspired me with good ideas for this script, but I still get some errors.
In my code i create new object and connect them to a parent. Right now a new parent is created for every new object. which is bad. I want to make sure that no new parent is created if a parent with a part of a certain name already exist. If it do exist I want to make that object the parent of the child. The actual script is longer but remove all parts that not relevant to this question.
private GameObject[] findParentContainer;
private GameObject parentContainer;
private GameObject child;
void Start()
{
findParentContainer = FindObjectsOfType(GameObject) as GameObject[];
}
public void Update(){
if (inputWeapon.Equals("gun")){
//Create a the new child 'PoolObjectGun', which need a 'gunContainer' parent
child = (GameObject)Instantiate(PoolObjectGun);
parentContainer = LookForParent("gun");
} else if (inputWeapon.Equals("rifle")){
child = (GameObject)Instantiate(PoolObjectRifle);
parentContainer =LookForParent("rifle");
} else if (inputWeapon.Equals("shotgun")){
child = (GameObject)Instantiate(PoolObjectShotgun);
parentContainer = LookForParent("shotgun");
}
//method that receives child name and returns its parent
private GameObject LookForParent (string s){
GameObject parent;
for (var i=0; i < findParentContainer.Count; i++){
if(findParentContainer[i].name.Contains("'s Pool")){
parent = findParentContainer[i]; //the found object at index i
}
}
return parent;
} }
Forgot to say that the errors are about the LookForParent method, and that my plan is to have a if statement within it that look for different names. The names should be "gun's pool" , "rifle's pool" and so on . So if the string input 's' is "gun", it will look for a object with a name that contains "gun's pool" and return that object.
Thank you!
Your answer
Follow this Question
Related Questions
What is the problem with the loop? 0 Answers
I want to make make a plant to grow after few seconds. 0 Answers
how to start counting from the last index the script stop on? 2 Answers
Odd NullReferenceException on FOR loop 0 Answers
for loop for game objects 1 Answer