- Home /
The question is answered, right answer was accepted
How to add an item to a list with a class/uJS struct?
I been trying to add a player to the list via .Add but nothing i do seems to work. So how would i add a player to that list?
import System.Collections.Generic;
var NumOfPlayers : int;
var PlayerTurn : boolean;
var Player :List.<PlayerInfo>;
class PlayerInfo{
var Name : String;
var Level : int;
var HP : int;
var TP : int;
var ATK : int;
var DEF : int;
}
function Start () {
Player.Add("Bob", 1, 10, 5, 10, 5);
}
function OnGUI(){
}
function Update () {
}
Thank you in advance.
Answer by meat5000 · Mar 01, 2015 at 04:31 PM
Your class needs a constructor to build the struct. It works well in uJS to extend System.ValueType.
Notice how the function matches the classname and how the values are passed as arguments to build your PlayerInfo.
//Making your own struct in uJS
#pragma strict
class PlayerInfo extends System.ValueType {
var Name : String;
var Level : int;
var HP : int;
var TP : int;
var ATK : int;
var DEF : int;
public function PlayerInfo( Name : String,
Level : int,
HP : int,
TP : int,
ATK : int,
DEF : int )
{
this.Name = Name;
this.HP = HP;
this.TP = TP;
this.ATK = ATK;
this.DEF = DEF;
}
}
//Basic List Examples
#pragma strict
import System.Collections.Generic;
public class ListTest extends MonoBehaviour
{
public var PlayerList :List.<PlayerInfo>;
private var paddingZero : PlayerInfo = PlayerInfo("ZeroElement", 0, 0, 0, 0, 0);
function Start ()
{
AddPlayerInfo(paddingZero);
}
function Update()
{
if(Input.GetKeyDown(KeyCode.Y))
{
AddPlayerInfo(paddingZero);
}
if(Input.GetKeyDown(KeyCode.U))
{
ChangeInfo("Steve", 2);
}
if(Input.GetKeyDown(KeyCode.I))
{
RemoveBlock(0);
}
}
function AddPlayerInfo(myPlayer : PlayerInfo)
{
this.PlayerList.Add(myPlayer);
}
public function RemoveBlock(playerIndex : int)
{
this.PlayerList.RemoveAt(playerIndex);
}
public function ChangeInfo(newName : String, playerID : int)
{
if(PlayerList[playerID] != null)
{
var tempHolder : PlayerInfo;
tempHolder = this.PlayerList[playerID];
tempHolder.Name = newName;
this.PlayerList[playerID] = tempHolder;
}
}
}
Ok i see how to do this now, Thank you very very much :D.
Ok i ran into a problem. When i try to remove/add HP it doesn't work. Im doing Player[0].HP -=1; Displaying stuff is no problem but when i go to remove/add nothing happens. EDIT: It gives me this error on the line i have Player[0].HP -= 1; "BCW0006: WARNING: Assignment to temporary." EDIT2: $$anonymous$$ay sound like a dumb question but how do i remove also? I tried Player[0].Remove(); Player[0].Remove; and Player.Remove(0);
Follow this Question
Related Questions
Help: items not getting added to list. 1 Answer
Check if Exists and if so, Add it to Other List 1 Answer
A node in a childnode? 1 Answer
can add to a list but not remove 1 Answer
List in prefab instantiated object not saving after Awake 0 Answers