How to use UI.Text as a prefab in Unity?
Solution 1
In new Unity3D UI
system, every UI
(Text
, Button
, Panel
etc.) component that will be renderer on screen must have a parent Canvas
component.
You actually do use such approach in your project, where you have Toolbar
, List
etc. that have parent called Canvas
and which I suppose has Canvas
component attached.
What you need to do is to move instantiated gameObject
to be child of other gameObject
that holds Canvas
component.
As there can be multiple components of Canvas
type, I would suggest to add possibility to assign root for instantiated objects inside your Script
.
Script:
//Drag and drop this from inspector; make sure that dragged gameObject
//has Canvas component in it or above it (in parent)
public Transform EntriesRoot;
void Start()
{
var entry = Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity);
//Put parent to our EntriesRoot
//EntriesRoot will be our new parent for entry in hierarchy
entry.transform.SetParent(EntriesRoot)
}
Solution 2
they need to be a child of a Canvas, that displays them.
// find canvas
GameObject canvas = GameObject.Find("Canvas");
// clone your prefab
GameObject text = Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity);
// set canvas as parent to the text
text.transform.SetParent(canvas.transform);
jeanl
Updated on June 04, 2022Comments
-
jeanl almost 2 years
I've tried using this
Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity);
It successfully created objects, as seen in my hierarchy. But I cannot see the text on the screen, even though there is a text assigned to it. I can only see an empty game object on the screen.
These screenshots show the game on play, and the selected object is the object instantiated through the script.
When I drag the prefab, it does not show anything on the scene. This happens to all my prefabs. The following are its components:
-
jeanl over 8 yearshow do i do that? the method Instantiate returns an UnityEngine.Object. That class does not have a field "enabled".
-
jeanl over 8 yearsI cant manipulate the object as a text because its type is not GUIText, rather it's Object. Casting doesnt work either
-
JeanLuc over 8 yearsif the prefab is enabled the cloned copy will be enabled too.
-
jeanl over 8 yearsSetParent is not supported in the latest version of Unity which is 5.3. Is there another way to instantiate this prefab as a child of the Canvas object?
-
mwilczynski over 8 yearsI'm using Unity 5.3.1 and it's definitely supported. You should indeed use SetParent on transform component, my bad (edited already). The way that is deprecated now is
transform.parent = otherTransform
nottransform.SetParent(otherTransform)
. What is the exact error? -
Procrastin8 about 5 yearsThere is a convenience to set the parent transform as part of
Instantiate
as well.GameObject text = Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity, EntriesRoot);