- Home /
How can I parent each item from one array to each item in another array?
I'm creating "two" arrays:
1) The first is simply an array of gameobjects with a specific tag
2) For the second (which is actually a generic list) I instantiate one prefab for every item that exists in the first array eg. if there are 7 items, 7 prefabs are instantiated. I then populate the generic list with all the instantiated prefabs.
Now what I would like to do is iterate through the generic list and parent each item to one item in the first array. But for some reason I can only manage to parent all the generic list items to one item in the array. Here is what I have so far:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class MapObjects {
public string objectTag;
public GameObject iconPrefab;
public GameObject[] objectsTagged;
public List<GameObject> iconPrefabs;
}
public class Map: MonoBehaviour {
public MiniMapObjects[] miniMapObjects;
// Use this for initialization
void Start () {
foreach(var element in miniMapObjects) {
element.objectsTagged = GameObject.FindGameObjectsWithTag(element.objectTag);
foreach(var taggedObjects in element.objectsTagged) {
GameObject objects = (GameObject) Instantiate(element.iconPrefab, transform.position, transform.rotation);
element.iconPrefabs.Add(objects);
}
for(var i = 0; i < element.iconPrefabs.Count; i++) {
icon.transform.parent = taggedObjects.transform;
}
}
}
The only similar solutions I can find online is parenting multiple array items to a single object, but I can't find any solutions about parenting multiple items to other multiple items. So how could I do this?
Answer by whydoidoit · Feb 20, 2014 at 06:16 AM
It feels to me like you should do this:
void Start () {
foreach(var element in miniMapObjects) {
element.objectsTagged = GameObject.FindGameObjectsWithTag(element.objectTag);
foreach(var taggedObjects in element.objectsTagged) {
GameObject objects = (GameObject) Instantiate(element.iconPrefab, transform.position, transform.rotation);
objects.transform.parent = taggedObjects.transform;
element.iconPrefabs.Add(objects);
}
}
}
In your code taggedObjects would refer to the last element in the array as the for loop has ended
Yes and yes, exactly right! I've been banging my head on the desk for the last few hours trying to figure this out. Thanks a lot :)
Your answer
Follow this Question
Related Questions
changing the camera's local position with Vector3 variables coming from an array 2 Answers
How do I have my players stats on the HUD? 0 Answers
How to determine what type of class is being interated through in an array of multiple classes 1 Answer
Displaying/getting elements of a list in a certain order 3 Answers
Inventory moving items bug. 0 Answers