Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...