正确的动作脚本来查找对象是否已经存在(在条件内部定义了局部变量)

发布于 2024-08-26 08:52:53 字数 824 浏览 7 评论 0原文

我有一个 Rect 对象,我想创建它并仅设置其属性一次。之后,我只想修改它的属性,因为它已经存在。这是我的总体想法

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

}

我尝试了几种方法和组合进行 if 条件检查:

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;` 

但无法获得所需的效果。每次运行此代码块时,根据我使用的版本,它要么给出“无法访问空对象”错误,要么 if 语句始终计算为 true 并创建一个新的 Rect 对象,然后我得到“正在创建“ 警报。

创建该矩形的正确方法是什么,但前提是该矩形不存在?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

摘星┃星的人 2024-09-02 08:52:53

您提供的代码中存在一些范围界定问题。

我认为你想要做的是:

var theRect:Rect;

...

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

你需要首先声明 theRect,但不必创建它。您可以稍后通过检查它是否为空来延迟实例化它。

按照您的设置方式,您在 if 语句中创建了 theRect 的本地版本,该版本在其他地方不可见。如果您没有事先声明它,您在尝试访问 theRect 时也会收到错误。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文