- Home /
What is the correct syntax to create a new object with a RectTransform from script?
What is the syntax for creating a new GameObject that has a RectTransform instead of a Transform in C#? I thought I could do this, but no:
RectTransform myObject = (RectTransform) new GameObject("myObject").transform;
Answer by kromenak · May 13, 2016 at 09:28 PM
I found that this works:
GameObject myGO = new GameObject("MyGO", typeof(RectTransform));
Haha, I was really, really, really hoping Unity would understand what I meant by that, and, fortunately, it seems it did :).
When you call "new GameObject", one of the overloads allows you to specify a set of Components that will be immediately added to the GameObject when it's created. Fortunately, it seems that adding "typeof(RectTransform)" here will correctly create the GameObject with a RectTransform out of the gate.
Answer by YoungDeveloper · Apr 17, 2015 at 12:32 AM
You can get it by
RectTransform rect = (RectTransform)this.gameObject.transform; //Casting to RectTransform
RectTransform rect = this.gameObject.GetComponent<RectTransform>(); //Using GetComponent
I am not trying to get the RectTransform of an existing object. I want to create a new gameObject with a RectTransform component attached ins$$anonymous$$d of the normal Transform. Any ideas how to do that? It always pops up with a regular Transform ins$$anonymous$$d.
$$anonymous$$y only solution to this so far is to have a Prefab of a RectTransform already created and then Instantiate a new RectTransform ins$$anonymous$$d of just trying to create a new GameObject ( I wanted my script to create a bunch of RectTransforms at runtime to populate a table).
I guess the problem is that if I create a gameObject and it starts out not being a child of a Canvas, it always has a Transform ins$$anonymous$$d of a RectTransform. I am not sure how you could create a new object starting as a child of a Canvas and add the RectTransform component explicitly.
You could create empty canvas object and store it in prefab, then initialize the prefab.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Character picking up box 0 Answers