- Home /
Change position of a text prefab added to a world space canvas via scripting
I'm building a scene where I want to render numbers 1-100 on the "floor" of the world space. I want to add them via scripting and position them in a grid. For now, I'm just rendering a single number which I'm trying to change the position of.
I'm able to instantiate the number (a Text component) from a prefab, set my Canvas as the parent to get it rendered in the right initial place and change the text. So far so good. But when I try change the position of the number, nothing happens. I've tried all the different ways of setting the position I could think of, but the number just stays in the initial corner keeping the position of the prefab.
I've also tried debugging in Visual Studio, and it seems like my calls to ie. anchoredPosition.Set() have no effect when I look at the position before and after the call via the debugger.
I'm a complete newbie and this might very well be something very simple I'm missing. Possibly canvas just work differently in world space than in the screen space. Any ideas?
using UnityEngine;
using UnityEngine.UI;
public class HundredBoard : MonoBehaviour {
public GameObject Number;
// Use this for initialization
void Start () {
this.generateBoard();
}
// Update is called once per frame
void Update () {
//this.generateBoard(); // Also tried this. It generates many numbers, but all in the same position.
}
void generateBoard() {
// These first lines works, number is instantiated, inserted and changed from "1" to "2"
var number = Instantiate<GameObject>(Number);
number.transform.SetParent(transform, false);
number.GetComponent<Text>().text = "2";
var ntransform = number.GetComponent<RectTransform>();
// None of these lines seem to have any effect
ntransform.offsetMax.Set(5, 5);
ntransform.offsetMin.Set(3, 3);
ntransform.anchoredPosition.Set(15, -23);
ntransform.anchoredPosition3D.Set(15, -23, 0);
number.GetComponent<Text>().rectTransform.position.Set(10, 0.15f, 0);
number.GetComponent<Text>().rectTransform.localPosition.Set(10, 0.15f, 0);
number.GetComponent<Text>().transform.position.Set(10, 0.15f, 0);
number.GetComponent<Text>().transform.localPosition.Set(10, 0.15f, 0);
number.GetComponent<Text>().rectTransform.anchoredPosition.Set(15, -23);
number.GetComponent<Text>().rectTransform.anchoredPosition3D.Set(15, -23, 0);
number.GetComponent<RectTransform>().localScale = Vector3.one;
number.GetComponent<RectTransform>().position.Set(10, 0.15f, 0);
number.GetComponent<RectTransform>().localPosition.Set(10, 0.15f, 0);
number.transform.position.Set(10, 0.15f, 0);
number.transform.localPosition.Set(10, 0.15f, 0);
}
}
I've uploaded a few screenshots here that might help clarify my question.