Assigning a script as a game object in Dictionary
Hello everybody,
I have a script called "HouseProperties" and I want all the objects with this script to be in my dictionary of string and gameobjects Dictionary<string, gameObject> houseProp = new Dictionary<string, gameObject>();
Is it possible to write somthing like GameObject houseValue = HouseProperties.gameObject
because this script is located on a gameobject?
I got an error of course, is there a way to write it correctly?
Thank you!
An error? I can't see one because you're not posting the code, the error and a way for us, out here, to read that.
That's said, it will also be better if we understand your goals, not just what you're doing. The reason is that your goal is a larger subject and what you're doing might not be the best way to reach that goal, and we might be able to recognize that.
Only if we know what the goal is, though.
So, what are you using the dictionary for, and have you considered if the transform might be a better hook (maybe, maybe not, but then I have no real idea what you're doing).
Answer by UnityCoach · Jul 28, 2018 at 10:15 PM
So, you want to collect all script instances, and store their game objects and names in a dictionary ?
You can use Linq for that, it makes it easy to read.
using System.Linq;
Dictionary<string, GameObject> housesDictionary;
HouseProperties [] allHouses = FindObjectsOfType<HouseProperties>();
housesDictionary = allHouses.ToDictionary(v => v.gameObject.name, v => v.gameObject);
Thank you @UnityCoach thats exactly what I've been looking for I'll test it and update the accepted answer
Your answer
Follow this Question
Related Questions
Unity C# how to Foreach variable in Model/Contract 0 Answers
How to get the Gameobject a script is attached to 2 Answers
Can't add Orbital script - "The script needs to derive from MonoBehaviour!" 0 Answers
How do you make a random 2D shape in Unity? 0 Answers
How to make multiple game object work with the same scripts? 0 Answers