Create models objects and get informations from them

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 :slight_smile:

Try to create interface any building inherits from, for instance Castle:Monobehavior, IBuilding
And then cast the instance of the class to IBuilding after loading the asset. In train now so I cannot write more details.


Edit: You could try this, seems to work for me (despite I feel this is not ideal approach).
I would prefer scriptable objects here. Some approach like here: SCRIPTABLE OBJECTS in Unity - YouTube

Anyway I run the following code on my PC and got appropriate results (if not missing something).

Building:

using System.Collections.Generic;
using System.IO;
using UnityEngine;

public abstract class Building : MonoBehaviour
{
    public abstract void Init();

    public void Init(Transform transform, string _name, Dictionary<string, int> _cost)
    {
        Name = _name;
        Cost = _cost;
        Icon = path + _name + ".ico";
        Image = path + _name + ".png";

        //commented out just to prevent runtime errors in my not completely set environment
        //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;
    }
}

Castle:

using System.Collections.Generic;

public class Castle : Building
{
    public Building building;

    public override void Init()
    {
        Init(transform, "Castle", new Dictionary<string, int>()
            {
                 {"Population", 500},
                 {"Wood", 1},
                 {"Rock", 3},
            }
         );
    }
  
    void Update()
    {

    }
}

ArrowTower:

using System.Collections.Generic;

public class ArrowTower : Building
{
    public Building building;

    public override void Init()
    {
        Init(transform, "Arrow Tower", new Dictionary<string, int>()
            {
                 {"Population", 4},
                 {"Wood", 2},
                 {"Rock", 5},
            }
         );
    }
  
    void Update()
    {

    }
}

Test:

using UnityEditor;
using UnityEngine;

public class TestBuildings : MonoBehaviour
{
    private void Start()
    {
        string nameOfSample = "Castle";
        var buildSamplePrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Resources/Buildings/" + nameOfSample + ".prefab");
        var instance = (Building) buildSamplePrefab.GetComponent(nameOfSample);
        instance.Init();
        int woodCost = instance.Cost["Wood"];
        string name = instance.Name;

        string nameofSampel1 = "ArrowTower";
        var buildsamplePrefab1 = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Resources/Buildings/" + nameofSampel1 + ".prefab");
        var instance1 = (Building)buildsamplePrefab1.GetComponent(nameofSampel1);
        instance1.Init();
        int woodCost1 = instance1.Cost["Wood"];
        string name1 = instance1.Name;
    }
}