- Home /
Problem passing a GameObject to another script
Hello all,
I have the following scenario:
ScriptA is attached to Object "A" and it's in charge of storing all the objects with a certain tag:
public List<GameObject> items;
private GameObject[] startingItems;
void Start()
{
items = new List<GameObject>();
startingItems = GameObject.FindGameObjectsWithTag("test");
foreach (GameObject element in startingItems)
{
items.Add(element);
}
}
Then I have ScriptB attached to Object "B": it gets the list from ScriptA and instantiates a UI Panel (prefab) for each element of the list. The instantiated panel has the screen coordinates of the element:
public GameObject ui_panelPrefab; //I'll drag this
private ScriptA scriptA;
void Start()
{
scriptA = GameObject.Find("A").GetComponent<ScriptA>();
foreach (GameObject element in scriptA.items)
{
PanelInst(element);
}
}
void PanelInst(GameObject obj)
{
Vector3 screenPosition = Camera.main.WorldToScreenPoint(obj.transform.position);
GameObject ui_panel = Instantiate(ui_panelPrefab, screenPosition, ui_panelPrefab.transform.rotation);
ui_panel.GetComponent<ScriptC>().screenPosition = screenPosition;
}
Now let's move to the instantiated panel. It has the following script attached that simply move the panel (changing its screen coordinates) as the "targetObject" moves:
public GameObject targetObj;
public Vector3 screenPosition;
void Update()
{
screenPosition = Camera.main.WorldToScreenPoint(targetObj.transform.position);
transform.position = screenPosition;
}
Now I need the "targetObj" above to be exactly the "obj" of the ScriptB. I did the dumb move and tried to add this line to the PanelInst() function of ScriptB:
ui_panel.GetComponent<ScriptC>().targetObj= obj;
...but it obviously doesn't work as intended: it passes only certain parameters of the "obj" gameobject (its name and starting position) but not the object itself, so the panel position in the last script never updates no matter if the "obj" moves (because "obj" in the second script and "targetObj" in the third script are not the same object).
How can I solve this problem? I can't try different setups (like the UI panel as child of the target object): I have to keep them separate but yet I need the UI panel to follow the screen coordinates of the target object.
Thanks in advance for your help and I'm sorry for the weird formatting of the code. I'm at work, I can't use Unity or code editors, I'm just typing here and I probably did mistakes or forgot things here and there. Just be aware that the code syntax is correct in Unity: it's just not behaving correctly.
Your answer
![](https://koobas.hobune.stream/wayback/20220613044746im_/https://answers.unity.com/themes/thub/images/avi.jpg)