- Home /
Converting String to a Game Object
Hi I"m making a game and I need to convert the contents of a string to a game object. Now the docs say that I'm not supposed to use the find function every frame for performance reasons. However it offers two alternatives 1. find with tag which is easy to implement but I don't see how its any more efficient. and 2. cache the result on startup which I can't use because I need to reference different game objects and I need to do it when the program is running.
So my question is whats the best way to convert a string to a gameobject?
You don't. Those two options ARE your options. Could you show us a script to make a better judgement call on this? A note: You can define a variable by going:
var myGameObject : GameObject;
in the beginning of your script, and you can change this reference throughout the script.
It's possible (I'm not certain of your needs) you need to use the Amazing (and FREE) "Unity Serializer" by Whydoidoit (one of the most genius members here).
Just google "whydoidoit unity serializer". It is used by very very many Unity devs, for things like "game saving" and so on.
Answer by DannyB · Dec 23, 2012 at 01:31 PM
There are several ways of doing this, and the approach will largely depend on your specific needs.
One way I am using is this:
Make all the game objects that need to be found a child of a master object.
All child objects should have a unique name.
The master object, on its Start(), uses foreach( Transform child in transform ) to find all its children, and add them to a Dictionary so that the key is the name of the object ( dictionary.Add(child.name, child.gameObject) )
From this point on, any script that needs an object by string, will simply get the dictionary['SomeObjectName']
Of course, this is the minimal and crud implementation, you should wrap the functionality in methods as per your individual design preferences.
Hi there! Can you give me some example (code), I need it too. Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613085814im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Convert String to GameObject[] type Array 2 Answers
Convert game object to string? 1 Answer
Convert GameObject to String? 2 Answers
Using Resources.load with a variable 1 Answer