- Home /
How to make a List Constructor?
I'm looking to make a constructor of a character which contains a list variable. How would I add this?
class Character
{
var name : String;
var hp : int;
var attacks : List.<Attacks> = new List.<Attacks>();
function Contructor (nameNew : String, hpNew : int, attacksNew : Attacks)
{
name = nameNew;
hp = hpNew;
attacks = attacksNew;
}
}
class Attacks
{
var name : String;
var power : int;
}
function Start ()
{
var player : Character;
player.Constructor("ben", 10, ????);
// I want to add two entrys to attacks List with name "fireball" and power 10.
}
Answer by fafase · Oct 04, 2014 at 02:00 PM
attacks.Add(new Attacks("Fireball", 10));
attacks.Add(new Attacks("Fireball", 10));
player.Constructor("ben", 10, attacks);
But you also need to add a ctor to your Attack class
public class Attacks
{
public function Attack(name :String, power:int){
this.name = name;
this.power = power;
}
var name : String;
var power : int;
}
edit:
player.Constructor("ben",10,new List<Attacks>(){
new Attacks("fireball",10),new Attacks("fireball",10)};
this is one line but it won't run faster though since the compiler still need to do each action oneby one.
I'm looking for a shorter hand version than Add. Something like this only using my Attacks Class if that is possible?
This Works -
var list : List.<String> = new List.<String>();
list = new List.<String>(["input", "2", "3"]);
This Doesnt - Try this example ins$$anonymous$$d to solve:
var list : List.<Attacks> = new List.<Attacks>();
list = new List.<Attacks>(new Attacks("name",0));
I get the error InvalidCastException: Cannot cast from source type to destination type.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Java Script command list 3 Answers
FindIndex in a List 1 Answer
Can I convert unityscript to boo? 0 Answers
Dynamically load UnityScript file 1 Answer