Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

unity3d - Unity c# control other scripts variables in realtime by registering variable

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;});
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...