Friday, September 22, 2006

Connecting two Flash Movies

The idea of this post is to explain the basic on how to use the class LocalConnection that helps us to communicate two different flash movies on the same html page.
- Create a new flash movie and call it "my_sender"
- Create a button on the stage with instance name "my_btn"
- First frame actionscript:

function my_function(my_parameter:String):Void {
var my_lC:LocalConnection = new LocalConnection();
my_lC.send("test_LC", "change_copy", my_parameter);
delete my_lC;
my_btn.onRollOver = function() {
my_function("You are rolling over a button on another SWF!")
my_btn.onRollOut = function() {
my_function("Rolled Out");

I have a function with a string as a parameter and inside I'm declaring my localConnection and sending three parameters:
- the name of my localConnection (test_LC)
- a method name
- the name of my parameter
I'm calling my_function when rolling over and out my_btn but my_function can be called in any other event.
That's it! save, publish and put on an html page.

Next steps:
- Create another flash movie and call it "receiver"
- Create a dynamic text field with instance name "my_copy"
- Add the following actionscript on the first frame of the main timeline:

my_copy.text = "This is a dynamic text box"
var my_lC:LocalConnection = new LocalConnection();
my_lC.change_copy = function(my_parameter:String) {
my_copy.text = my_parameter

Put a string to show on my text field on load so we know where the text box is;
Add an instance of the localConnection class with the variable "my_LC".
Then I use the parameters sent by my first movie to give a new value to my_copy;
And connect to the "localConnection" created.

That's it!
See the example below:

Second Movie

The localConnection class can be very useful and can help us for instance with the flow when loading different flash movies on the same html page, we can start loading another movie as soon as the first one has finished loading.


1 comment:

Jase said...

Hi Ernesto. Thanks, that was really helpful.