Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In real time, i want to register a variable to my other scripts at start and want it to be controlled at realtime by other script.

public float leftTime;

MyManager.RegisterVariable(leftTime);

thats all, now i want my manager to control this variable by it self in update. How can i make this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

Keep setter and getter functions in MyManager then take them and save them in RegisterVariable:

// in MyManager
static Action<float> varSetter;
static Func<float> varGetter;

static void RegisterVariable(Action<float> setter, Func<float> getter)
{
    varSetter = setter;
    varGetter = getter;
}

static void SomeFunction()
{
    float oldFloatValue = varGetter();
    float newFloatValue = oldFloatValue + 5f;
    varSetter(newFloatValue);
}

Then, when you call RegisterVariable, pass getter and setter. I recommend using anonymous functions if you don't plan on calling this frequently.

// in other script

float foobar = 5f;

void SomeOtherFunction()
{
    MyManager.RegisterVariable((f) => {foobar = f;}, ()=> {return foobar;});
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...