In C# with Unity i am trying to create a Dictionary of Classes.
All the classes inherit from a base Class (Building Script) which has a number of Virtual Methods
i have set up my Dictionary thus:
Dictionary<string, BuildingScript> buildingScripts = new Dictionary<string, BuildingScript>();
And am trying to add to the Dictionary thus:
buildingScripts.Add("Farm", FarmScript);
buildingScripts.Add("Hunter", HunterScript);
buildingScripts.Add("Fisher", FisherScript);
The compiler is recongising the inheritance so i am trying to work out what i have missed.
The error messages are:
- error CS0119: Expression denotes a
type', where a
variable',value' or
method group' was expected- The best overloaded method match for 'System.Collections.Generic.Dictionary.Add(string, BuildingScript)' has some invalid arguments
- Argument
#2' cannot convert
object' expression to type `BuildingScript'
Your dictionary has been declared as Dictionary<string, BuildingScript>
, so its value should be an instance of BuildingScript
.
Consider difference: FarmScript
itself is type, but new FarmScript()
is instance of that type.
So your code should look like:
buildingScripts.Add("Farm", new FarmScript());
buildingScripts.Add("Hunter", new HunterScript());
buildingScripts.Add("Fisher", new FisherScript());
Although not really shown in the posts, but they seem to be the classes to me:
FarmScript //class
HunterScript //class
FisherScript //class
while what you need are the instances:
FarmScript farmScript = new FarmScript(); //instances of the classes
HunterScript hunterScript = new HunterScript();
FisherScript fisherScript = new FisherScript();
This should be OK:
buildingScripts.Add("Farm", farmScript);
buildingScripts.Add("Hunter", hunterScript);
buildingScripts.Add("Fisher", fisherScript);
OK, solved it myself.... though if there are better ways of doing this (and i sure bet there are) then please post them so i can learn.
I changed the Add's to the Dictionary like this:
FarmScript bs1 = new FarmScript();
DictionaryStore.buildingScripts.Add("Farm", bs1);
HunterScript bs2 = new HunterScript();
DictionaryStore.buildingScripts.Add("Hunter", bs2);
FisherScript bs3 = new FisherScript();
DictionaryStore.buildingScripts.Add("Fisher", bs3);
Problems all solved!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.