I’m trying to get a gameobject that has the user’s username as the name of the object. I would like the use the value of a variable as the name of the object.
string username = "PlayersUsername";
Player = GameObject.Find(username).GetComponent<GameObject>();
Is there a possible way to do this? It always gives me an ‘Undefined’ error.
Thanks in advance!
Find returns a GameObject. You don’t need to do the GetComponent part.
Okay, but this doesn’t work either:
PlayerScript = GameObject.Find(username).GetComponent<UnmountedController>();
“doesn’t work” is not super useful diagnostics-wise. Maybe:
- what you expect to happen
- what is happening
- why you think it should work (full code + screenshot of hierarchy while the game is running)
- maybe some debug.log statements to illustrate steps along the way, such as the contents of ‘username’ variable the moment before the code above executes.
Design wise, putting the user’s name in an internal field and then using it as a search string is not a good pattern to follow. What are you trying to do with such a construct? Why not make a manager that tracks GameObjects and correlates them to a known set of names?