Skip to main content
Inspiring
September 27, 2015
Answered

Random Number Generator throwing error

  • September 27, 2015
  • 1 reply
  • 393 views

In my code I have a function chooseTarget which parses through all children of the stage, determines if they have _enemy in their instance name, adds it to an array, and returns a random index of that array.

function chooseTarget():Object

{

  var listofenemies:Array;

  for(var n:uint = 0; n < stage.numChildren; n++){

  if(stage.getChildAt(n).name.indexOf('_enemy', 0) >= 0)

  {

  listofenemies.push(stage.getChildAt(n));

  trace(listofenemies);

  }

  }

  if(n == stage.numChildren)

  {

  var ran:Number = Math.floor(Math.random() * (listofenemies.length - 0 + 1)) + 0; //this gives an error

  var curtarg:Object = listofenemies[ran]

  }

  return curtarg;

}

When this function is called, however, I get

TypeError: Error #1009: Cannot access a property or method of a null object reference.

Pointing to the ran variable.

What is going on?

This topic has been closed for replies.
Correct answer kglad

there's no array.  to remedy:

var listofenemies:Array=[];

1 reply

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
September 27, 2015

there's no array.  to remedy:

var listofenemies:Array=[];

mcdermittAuthor
Inspiring
September 27, 2015

All right! It works like a charm now.

Thank you!

kglad
Community Expert
Community Expert
September 27, 2015

you're welcome.