0
votes

I have a Rect object that I'd like to create and set its properties only once. After that, I want to just modify its properties since it already exists. This is my general idea

if(theRect == undefined){

  Alert.show("creating");

  var theRect:Rect = new Rect();
  //then set properties
  addElement(theRect); //then add it using addElement because addChild() does not work

} else {

  Alert.show("updating");

  //no need to create it since it's already been created
  //just access and change the properties

}

I tried several ways and combinations for the if conditional check:

if(theRect == undefined){
if(theRect == null){
declaring and not declaring `var theRect:Rect;` before the if check
declaring and instantiating to null before the if check `var theRect:Rect = null;` 

but can't get the desired effect. Everytime this code block runs, and depending on which version I've used, it either gives me a "can't access null object" error or the if statement always evaluates to true and creates a new Rect object and I get the "creating" Alert.

What's the right way of creating that Rect but only if doesn't exist?

1

1 Answers

2
votes

You have some scoping issues in the code you presented.

What I think you want to do is:

var theRect:Rect;

...

if(theRect == null)
{
    theRect = new Rect();
    ...
}
...

You need to first declare theRect, but you don't have to create it. You can instantiate it lazily later by checking if it is null.

The way you have it set up, you created a local version of theRect inside your if statement that would not be visible elsewhere. You will also get an error trying to access theRect if you did not declare it beforehand.