Question 1: How to delete an object?
There are many ways to delete objects. Let's do some simple operations step by step.
There is a button in the scenario, we click the button, and then delete a MC
Steps:
Put a button named BTN in the scenario
Create a MC object and add it to the display list
- Package
- {
- Import flash. display. movieclip;
- Import flash. Events .*;
- Import flash. display. simplebutton;
- Public class example4 extends movieclip
- {
- Private var mymc: Mc;
- Public Function example4 ()
- {Init ();
- BTN. addeventlistener (mouseevent. Click, onclick );
- }
- Private function Init (): void
- {
- Mymc = new MC ();
- Addchild (mymc );
- Mymc. x = 250;
- Mymc. Y = 200;
- }
- Private function onclick (E: mouseevent): void
- {
- Removechild (mymc); // Delete the MC object
- }
- }
- }
It's easy to use removechild to delete the MC object, but when we click the button again, we can find that such code will have some errors.
Argumenterror: Error #2025: The provided displayobject must be a sub-level of the caller.
At flash. display: displayobjectcontainer/removechild ()
At example4/: onclick ()
The problem is that we have deleted the object, so when we call the delete object, the object does not exist.
To avoid this problem, we need to modify the code
- Private function onclick (E: mouseevent): void
- {If (mymc! = NULL)
- {Removechild (mymc );
- Mymc = NULL;
- }
- }
Determines whether the object is null, so that even if you click the button again, the object will remain in the memory after deletion, so we assign null to it to complete some simple deletion.
Question 2: How to delete multiple objects?
According to the above method, we know that we can use the removechild method to delete objects and see how to delete multiple objects?
What are the following results?
- Package
- {
- Import flash. display. movieclip;
- Import flash. Events .*;
- Import flash. display. simplebutton;
- Public class example4 extends movieclip
- {
- Private var mymc: Mc;
- Public Function example4 ()
- {
- Init ();
- BTN. addeventlistener (mouseevent. Click, onclick );
- }
- Private function Init (): void
- {
- For (var I: Int = 0; I <5; I ++)
- {
- Mymc = new MC ();
- Addchild (mymc );
- Mymc. x = 50 + I * mymc. width;
- Mymc. Y = 200;
- }
- }
- Private function onclick (E: mouseevent): void
- {
- If (mymc! = NULL)
- {
- Removechild (mymc );
- Mymc = NULL;
- }
- }
- }
- }
Obviously, if you run the code like this, it will only delete an object. How can you delete the object one by trying to change the result?
Note that this code is faulty. Can you solve it by yourself?