I want to access the value of a static field in other static methods running on the same thread. An example is in the code below :
The first class in this script is ClassA
. ClassA's job is to compare two Rect
value , If there is inequality between tho two compared Rect
values then a public boolean is set to true;
in classA , IsRectChanged
is a bool method which takes a parameter object of type Rect
and compares it to StoredRect
which is a Rect
. The method returns true when storedRect
and the Rect
value of IsRectChanged
do not match.
public class ClassA
{
private Rect storedRect;
public ClassA() { }
public bool IsRectChanged(Rect rect)
{
bool isChanged = !rect.Equals(storedRect);
if(isChanged)
{
storedRect = rect;
}
return isChanged;
}
}
This is ClassB
We create a static field of ClassA
named isRectChanged
in ClassB
.
Do not change the structure of the MethodB
in ClassB. Consider the fact that 50 other methods in static and non static classes must use a ClassA
field . Needing to change the structure of ClassB
in order to make the code work is would be counterproductive.
public static class ClassB
{
private static ClassA RectHelper = new ClassA();
public static void MethodB(Rect yourRect)
{
if(RectHelper.IsRectChanged(yourRect))
{
Debug.Log("Changes were made");
}
}
}
ClassC
, ClassD
and ClassE
are running on the same thread.They both call ClassB.MethodB
and assign a new Rect
in the parameter of MethodB
.
Because ClassC
,ClassD
and ClassE
are call ClassB.MethodB
and assign a new Rect
in the parameter of MethodB
. They each override the storedRect
value of the static field ClassA RectHelper
.
Because of this ,ClassA
RectHelper.IsRectChanged
will always be true.
How do I work around this without having to make ClassB
's ClassA
's and ClassE
's MethodB
non static ?**
public class ClassC
{
public void UpdateEverFrame()
{
ClassB.MethodB(new Rect(0, 0, 20, 20));
}
}
public class ClassD
{
public void UpdateEverFrame()
{
ClassB.MethodB(new Rect(100, 100, 10, 10));
}
}
Here in ClassE
ClassB.MthodB
is called in two UpdateEverFrame
methods , one of which takes in a int parameter . They override each other if they are called simultaneously, so the system will believe that IsRectChanged
is true and will always return true. which is a big problem.
We dont want IsRectChanged
to be overridden , We want each Call of ClassB.MethodB
to be treated as if it are not static so that IsRectChanged
is never overridden
public class ClassE
{
public void UpdateEverFrame()
{
ClassB.MethodB(new Rect(0, 0, 20, 20));
}
public void UpdateEverFrame(int i)
{
ClassB.MethodB(new Rect(100, 100, 10, 10));
}
}
In my question When I say 'access a unique value of a static property' I am talking about ClassB.RectHelper
.
I know that ClassB.RectHelper
is STATIC so the value will be shared between the classes ClassC
, ClassD
and ClassE, whenever they call MethodB
. But can we work around this so that ClassC
and ClassD
so not override the storedRect
value in ClassA ?