- Home /
Question by
refreshcreations · Jun 26, 2011 at 03:29 PM ·
arraybeginnerclass
Unity 3D Newbie Quetion in javascript.
Trying to use classes inside scripts to display mutliple objects.
They seem to create successfully although only the last one displays on screen, using GUI Functios for this currently.
I'm stuck as to why i only see the last invader on screen and the others simply don't appear.
Did some testing with Debug.Log and they all seem to be crated okay. Seems to be a sticking block for me :(
////////////////////////////////////////////////////////////////////////////////
//Global declarations
static var MAX_ENEMIES = 40;
var tex_enemy:Texture2D;
// SPRITE CLASS START
class CSprite{
var mytexture:Texture2D;
var x =0.0f;
var y= 0.0f;
var xspeed = 0;
var yspeed = 0;
var alive =1;
function CSprite(){
}
function Init(inx, iny, inalive){
mytexture = Resources.Load("invader");
x = inx;
y = iny;
alive = inalive;
}
function Display(){
if (alive == 1){
GUI.DrawTexture(Rect(x,y,8,8),mytexture);
}
}
}
// SPRITE CLASS END
static var enemies = new Array();
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//Inside Start
tex_enemy=Resources.Load("invader");
var tempenemy = new CSprite();
tempenemy.Init(100,100,1);
tempenemy.mytexture = tex_enemy;
for (i=0; i<MAX_ENEMIES; i++){
enemies.push(tempenemy);
enemies[i].Init((i*16), 100, 1);
enemies[i].mytexture = tex_enemy;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//Inside ONGui
for (i=0; i<MAX_ENEMIES; i++){
enemies[i].Display();
}
////////////////////////////////////////////////////////////////////////////////
Comment
Best Answer
Answer by Bunny83 · Jun 26, 2011 at 03:57 PM
You just created one instance of your CSprite class but pushed it several times in the array. That's why all elements points to the same sprite. That's why only the last set values are used.
for (i=0; i<MAX_ENEMIES; i++){
var tempenemy = new CSprite();
tempenemy.Init((i*16), 100, 1);
tempenemy.mytexture = tex_enemy; // You set the texture already in Init so i don't get why you do this here again.
enemies.push(tempenemy);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612122256im_/https://answers.unity.com/themes/thub/images/avi.jpg)