Hello,
I working on an RTS game and I’m stuck on a conceptual problem.
I have a class like this:
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class Building {
public Building(Transform transform, string _name, Dictionary<string, int> _cost)
{
Name = _name;
Cost = _cost;
Icon = path + _name + ".ico";
Image = path + _name + ".png";
transform.GetComponent<SpriteRenderer>().sprite = CreateSprite(Image);
}
private string path = @".\Assets\Graphics\Buildings\";
public string Icon { get; private set; }
public string Image { get; private set; }
public string Name { get; private set; }
public Dictionary<string, int> Cost { get; private set; }
public int Production { get; set; }
public Sprite CreateSprite(string pathImage)
{
// read image
byte[] bytes = File.ReadAllBytes(pathImage);
// create texture
Texture2D texture = new Texture2D(8000, 8000, TextureFormat.RGBA32, false);
texture.filterMode = FilterMode.Trilinear;
texture.LoadImage(bytes);
// create sprite from texture
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2());
return sprite;
}
}
After that, I create a prefab with a script include a new instance of this class for every building:
using System.Collections.Generic;
using UnityEngine;
public class Castle : MonoBehaviour {
public Building building;
// Use this for initialization
void Start ()
{
building = new Building(transform, "Castle",
new Dictionary<string, int>()
{
{"Population", 500},
{"Wood", 1},
{"Rock", 3},
}
);
}
// Update is called once per frame
void Update ()
{
}
}
Later I need to get informations from the variable “building” (in the Castle class) which is an instance of the class Building. All prefab building have these same variable and inherited from Building.
I try to get these informations from runtime with just the name of the script in generic way:
GameObject buildSamplePrefab = (GameObject) AssetDatabase.LoadAssetAtPath("Assets/Resources/Buildings/" + nameOfSample + ".prefab", typeof(GameObject));
int woodCost = buildSamplePrefab.GetComponent(nameOfSample).building.Cost["Wood"];
But this obviously does not work. I’m sure I miss something but I don’t find where. Any idea is welcome.
I hope it’s understandable.
Thank you for your help