Search Unity

Accessing TextMesh.text inside a instance of a prefab

Discussion in 'Scripting' started by twintower31, Mar 31, 2008.

  1. twintower31

    twintower31

    Joined:
    Oct 31, 2007
    Posts:
    89
    Hello,

    I'm trying to get and set the text of a TextMesh that belongs to a prefab in C#.
    The "tree" of the prefab (my character) is like that :

    MyCharacterPrefab
    - Number (<=> where Number is the 3Dtext TextMesh)
    - CharacterController
    - ...

    I tried to use the following code in C# found on the forum ,
    but an error occurs on the text property access:

    Code (csharp):
    1.  
    2. GameObject prefabinstance=(Prefabtype)instantiate(MyCharacterPrefab,....);
    3. ...
    4. TextMesh textMeshComponent = prefabinstance.GetComponent(typeof(TextMesh)) as TextMesh;
    5. textMeshComponent.text = "Testing";
    6.  
    And at runtime :
    MissingComponentException : there is no "TextMesh" attached to the MyCharacterPrefab (Clone) game object, but a script is trying to access it.

    NB : The prefabinstance is well created and usable.


    Thanks for your help,
     
  2. Shannon

    Shannon

    Joined:
    Dec 20, 2007
    Posts:
    21
    I am trying to do something similar in C# and getting similar (frustrating) results. After reading your post in the context of other search results for this topic, I came up with the following code that works for me at runtime:

    Code (csharp):
    1.  
    2. private string distanceText;
    3. private TextMesh textMeshReference;
    4.  
    5. void Start () {
    6.     distanceText = Mathf.Floor(transform.position.z).ToString();
    7.     textMeshReference = (TextMesh)GetComponent(typeof(TextMesh));
    8.     textMeshReference.text = distanceText;
    9. }
    The TextMesh is a child of a target. At run time the TextMesh shows its z depth in meters.
     
  3. twintower31

    twintower31

    Joined:
    Oct 31, 2007
    Posts:
    89
    Hi Shannon,
    Thanks you for your response,
    but I already tried your solution.
    I think it works with a Textmesh that is not a prefab.

    For my case, I found this solution :
    Code (csharp):
    1.  
    2. TextMesh textMeshComponent=goCurrentPlayer.GetComponentInChildren(typeof(TextMesh)) as TextMesh;
    3.  textMeshComponent.text = strPlayerName;
    4.  
    Hope it helps someone.
     
    tjasajereb2 and fredsharples like this.
  4. JJ Hou

    JJ Hou

    Joined:
    Jul 7, 2011
    Posts:
    45
    Hello,
    I am using 3D Text to show tweets on the screen in curve. I wonder if there is way to do it easier. The tweets are got from a server database and the code is to get the tweets amd show them in curve. I tried to create 3D text prefab, but I haven't found the way to change the text. I wonder if there are ways to change the text in the prefab or other ways. I know how to change text for a 3D Text Gameobject, but that is complex for my situation.

    Thanks