Hello,
I am new to Actionscript and need to update a variable within a class from another class.
By class, I mean the .as files.
All I can do is read a variable within a class from the timeline.
I would appreciate any help. I'm running out of time ![]()
generally, the two classes need to share something in common. if the two classes are totally unrelated to each other there are still ways to solve the problem but typically they are related.
if you have a reference to class1 inside class2, then you can update any public variable in class1 using the class2 reference and dot notation. that's not good practice but it's easy to understand.
somewhat better is to use a private variable in class1 and add a public setter in class1 that class2 can use to update that variable. you can then do some error checking in your setter.
and there's a lot more that can be said on the subject.
Hi,
In order to solve this issue, there are many ways, but what we do at our level is to use static Class.
Means we kept our common variables in a static class and make them public static, so those variables are accessible in the complete project, you can change their value from anywhere in the project.
And if you want more explanation on this topic, tell me, because there is a lot of stuff on this.
VIPUL
Here's an example of one class instantiating another class and changing a variable, just using public for ease.
// Class A in a.as
package
{
public class A
{
public var SomeNumber:Number = 100;
public function A()
{
}
}
}
// Class B in b.as that instantiates A and then changes SomeNumber
package
{
public class B
{
private var aRef:A = new A(); // instantiate a new "A" in the variable "aRef"
public function B()
{
// trace the initial value of SomeNumber
trace(aRef.SomeNumber); // traces 100
// set it to a new value
aRef.SomeNumber = 500;
trace(aRef.SomeNumber); // traces 500
}
// provide a public method to set the reference to A if desired, used below
public function SetReference(ref:A):void
{
aRef = ref;
}
}
}
The tricky part comes in making sure you pass the "correct instantiated reference" to an object to the class that wants access to it. In this example the B class directly instantiates the A class and changes it.
However typically on a frame script on the timeline you'd instantiate A and B. Then instead of B instantiating A, you'd pass a reference of it.
e.g. frame script on the main timeline:
// init objects
var aRef:A = new A();
var bRef:B = new B();
// pass a reference of A to B using that SetReference() method above:
bRef.SetReference(aRef);
Now you've passed a reference of A into B and B dutifully updated its instance of A. Now any other frame scripts affecting aRef will also affect the reference B has to it because you're not creating 2 separate A's. You're creating just 1 and using that single reference.
Confusing, I know, but read it a few times.
North America
Europe, Middle East and Africa
Asia Pacific