UnityScript nested objects best practice
Hi there :)
I just can't get my head around this: In reference to this question
Problem is the following:
Say you have a player, that player has an inventory, the inventory has weapons, and those weapons have stats.
Disregarding creating equivalent GameObjects and assigning scripts/values to these and so forth. how would I go about making that player?
I come from pure javascript.
So it could just be:
var player = {};
player.inventory = {};
player.inventory.weapons = {};
player.inventory.weapons["axe"] = {damage = 10, price = 5};
// then we could access the axe price stat with: player.inventory.weapons["axe"].price;
Nested classes, dictionary/hashtable, or is the best way to go to link everything to respective GameObjects :/
Thanks.
Answer by jmonasterio · Jan 03, 2016 at 03:25 AM
Everywhere where you have = {}, you're creating a new object. So in C# it would be like:
// Some simple object to hold data. Could be more complex and inherit from MonoBehaviour, etc.
class Player { public string name; // Other props here. };
class Inventory { public Dictionary <string,Weapon> Weapons; };
class Weapon { public int damage; public int price };
// Create the objects and initialize members.
var player = new Player();
player.inventory = new Inventory();
player.inventory.weapons = new Dictionary<string, Weapon>();
player.inventory.weapons.Add( "axe", new Weapon() { damage = 10, price =5 });
(forgot to thank you; Thank you very much :D) Declare the objects first, got it. Although, need to reference the child class in the parent one as well.
class Player {
var name : String;
var inventory : Inventory;
}
class Inventory {
var weapons : Weapons;
}
class Weapons {
var weapon : Weapon;
}
class Weapon {
var damage : int;
var price : int;
function Weapon(dam : int, pri : int){
damage = dam;
damage = pri;
}
function Weapon(){
damage = 10;
price = 10;
}
}