Search Unity

Setting UI Text Parent to Canvas

Discussion in 'UGUI & TextMesh Pro' started by myrupsaple, Dec 26, 2018.

  1. myrupsaple

    myrupsaple

    Joined:
    Dec 24, 2018
    Posts:
    1
    I just started using Unity, and have been trying to add various features onto the "Space Shooter" tutorial for practice. I'm trying to make it so that a number appears whenever the player destroys an object. For example, "+10" should appear at the collision spot of an astroid and a player's bolt. To do this, I have the following function (as suggested by other posts):
    Code (CSharp):
    1. void displayText(Text textField, Collider otherObject)
    2.     {
    3.         Text tempTextField = Instantiate(textField, otherObject.transform.position, otherObject.transform.rotation) as Text;
    4.         tempTextField.transform.SetParent(renderCanvas.transform, false);
    5.     }
    textField is the prefab of the text object that displays the "+10", otherObject is the object collider that triggered the OnTriggerEnter function, and renderCanvas is a public Canvas object that holds a reference to an empty Canvas prefab.
    displayText is called within OnTriggerEnter whenever the collision of two objects warrants points being awarded to the player. However, despite parenting an instance of the prefab (and not the prefab itself), I get the following error in the console each time the text should pop up:
    Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption

    From what I've read, this function should work. Or am I getting the error because the renderCanvas itself is a prefab? If this is the case, then I'm not sure what to do. I've even tried creating a copy of the canvas and setting it as the parent instead:
    Code (CSharp):
    1.     void displayText(Text textField, Collider otherObject)
    2.     {
    3.         Text tempTextField = Instantiate(textField, otherObject.transform.position, otherObject.transform.rotation) as Text;
    4.         Canvas tempCanvas =  renderCanvas;
    5.         tempTextField.transform.SetParent(tempCanvas.transform, false);
    6.     }
    Using Unity 2018.3.0f2