This is a more specific question to one I made earlier that was never answer. I’m hoping since the scope is more specific, I’ll have more luck.
I have the following text that takes a prefab and places it in a list of game objects (since I’m watering this down from my main script) and then places it inside the canvas at the spot I tell it to.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class TesterScript : MonoBehaviour {
public GameObject canvas;
public GameObject panel;
public List<GameObject> Plant_panel_list = new List<GameObject>();
int [] placement = new int[] {250,300};
// Use this for initialization
void Start () {
int xspot = placement[0];
int yspot = placement[1];
Plant_panel_list.Add((GameObject)Instantiate(panel));
Plant_panel_list[0].transform.SetParent(canvas.transform);
Plant_panel_list[0].transform.SetAsFirstSibling();
Plant_panel_list[0].transform.position = new Vector3(xspot,yspot,0);
}
// Update is called once per frame
void Update () {
}
}
Inside this prefab, there are 2 text game objects called Text1 and Text2. my question is how do I access those objects so I can control the text.
This should give you what you need. You need to create an extra component to be placed on your panel object. After this you reference the components you need, I.E. your text components and change their text this way.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TesterScript : MonoBehaviour
{
public GameObject canvas;
public GameObject panel;
public List<GameObject> Plant_panel_list = new List<GameObject>();
int[] placement = new int[] { 250, 300 };
// Use this for initialization
void Start()
{
int xspot = placement[0];
int yspot = placement[1];
Plant_panel_list.Add((GameObject)Instantiate(panel));
Plant_panel_list[0].transform.SetParent(canvas.transform);
Plant_panel_list[0].transform.SetAsFirstSibling();
Plant_panel_list[0].transform.position = new Vector3(xspot, yspot, 0);
//here are the changes
TestPanel testPanel = Plant_panel_list[0].GetComponent<TestPanel>();
testPanel.SetTextOne("Here is the value of test one");
testPanel.SetTextTwo("Here is the value of test two");
}
// Update is called once per frame
void Update()
{
}
}
//place this on your panel object
public class TestPanel : MonoBehaviour
{
//assign these in the inspector of your prefab
public Text TextOne;
public Text TextTwo;
public void SetTextOne(string val)
{
TextOne.text = val;
}
public void SetTextTwo(string val)
{
TextTwo.text = val;
}
}