0

I have a playing card prefab which contains a TextMeshPro object for displaying a number. I wish to instantiate the prefab and change the number. In some cases I can change the number, in other cases I cannot.

I started by creating a sample scene to experiment with the code for changing the text. This scene contains an object with a script for changing the text. In the Start method of the script I instantiate the prefab and change the number. This works fine. See the code below.

 Vector3 position = new Vector3(0.0f, 0.0f, 0.0f);
 card = Instantiate(cardPrefab, position, Quaternion.Euler(0.0f, 180f, 0f));
 GameObject.Find("UpperLeftNumber").GetComponentInChildren<TextMeshPro>().text = "88";

When I move the code from the sample scene to my game scene, it does not work. In the game scene, the code is called in a ClientRPC.

I have tried many combinations of SetActive(true/false), SetText, ForceMeshUpdate, and SetAllDirty. Nothing works, the number doesn't change. If there is a trick to using one or more of these methods, then please help me. Perhaps I am using them in the wrong order?

There seems to be a distinct difference between instantiating in Start rather than in a ClientRPC. Can someone explain this difference?

dkalkwarf
  • 313
  • 2
  • 11
  • Is there more than one "UpperLeftNumber" in your scene? Because, if so, your GameObject.Find function will pick one indeterminately... not necessarily the one you just spawned. – Louis Ingenthron Mar 09 '23 at 15:26

2 Answers2

1

If you have an ClientRPC this can be called only from a server machine. Seems like you are making a Multiplayer application/game.

You can find more info here https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/clientrpc/index.html

If that's not the issue you can use the object that you just spawned to retrieve the TextMeshPro. This in case you have multiple objects in your scene named as "UpperLeftNumber".

 Vector3 position = new Vector3(0.0f, 0.0f, 0.0f);
 card = Instantiate(cardPrefab, position, Quaternion.Euler(0.0f, 180f, 0f));

Transform[] transforms = card.GetComponentsInChildren<Transform>()

foreach(Transform t in transform){
  if(t.name.equals("UpperLeftNumber")){
   t.GetComponentInChildren<TextMeshPro>().text = "88";
}

}
0

Both responders hit on the problem: there are two UpperLeftNumber objects in the scene.

The fix was just what Giuseppe provided: use card.GetComponentsInChildren() rather than GameObject.Find()...

dkalkwarf
  • 313
  • 2
  • 11