This is my struct that I have created.
public struct Bar
{
private static float deltaTime = 1.0f;
private static bool AutoRun = false;
private static bool AutoRunBought = false;
private static bool Start = false;
// DELTA TIME
public float GetDeltaTime()
{
return deltaTime;
}
public void SetDeltaTime(float _dt)
{
deltaTime = _dt;
}
public void IncrementDeltaTime(float _deltaIn)
{
deltaTime += _deltaIn;
}
public void DecrementDeltaTime(float _deltaIn)
{
deltaTime -= _deltaIn;
}
// AUTO RUN
public bool GetAutoRun()
{
return AutoRun;
}
public void SetAutoRun(bool _autoBought)
{
AutoRunBought = _autoBought;
}
public bool GetAutoRunBought()
{
return AutoRun;
}
public void SetAutoRunBought(bool _autoBought)
{
AutoRunBought = _autoBought;
}
// START
public bool GetStart()
{
return Start;
}
public void SetStart(bool _start)
{
Start = _start;
}
}
In my other class I create an instance of that by calling
scr_Globals.Bar[] myBars = new scr_Globals.Bar[2];
in my Update I am doing
if (myBars[0].GetAutoRun() == true)
{
myBars[0].IncrementDeltaTime (incrementBar1);
if (myBars[0].GetDeltaTime () > 40.0f) {
myBars[0].SetDeltaTime (1.0f);
globals.IncrementTotalMoney(1.0f);
}
}
else
{
if (myBars[0].GetStart() == true)
{
myBars[0].IncrementDeltaTime (incrementBar1);
if (myBars[0].GetDeltaTime () > 40.0f) {
myBars[0].SetDeltaTime (1.0f);
globals.IncrementTotalMoney(1.0f);
myBars[0].SetStart(false);
}
}
}
This above code is done for both of the buttons, so I have the same code but for position 1 of the array. and I have a button that is created from Unity's UI and when it is clicked it activated a function I have created that sets one of the bools on. That code looks like this
public void OnButton1Click()
{
myBars[0].SetStart (true);
}
Whenever the button is clicked and calls that function it sets both myBars[0] and myBars[1] SetStart to true. Any assistance is appreciated, thanks a lot.
Your fields are all static:
private static float deltaTime = 1.0f;
private static bool AutoRun = false;
private static bool AutoRunBought = false;
private static bool Start = false;
So if you write:
Bar x = new Bar();
Bar y = new Bar();
x.SetStart(true);
bool b = y.GetStart();
... then b
will be true. The value returned by GetStart
doesn't depend on the value you call it on at all...
You don't want those fields to be static - they're meant to represent part of the state of each value, right?
I'd actually advise against mutable structs too, but that's a different matter. I'd also advise against all those GetXyz
/SetXyz
methods - learn about C# properties instead.
If you're new to C#, I'd really recommend learning it outside the Unity environment first - install Visual Studio 2015 Community Edition and learn about the basics of the language via console apps etc, with the aid of a good book. You'll be in a much simpler environment to experiment with, and you won't constantly be wondering whether odd behaviour is due to C# or Unity.
See more on this question at Stackoverflow