繁体   English   中英

unity c# 通过注册变量实时控制其他脚本变量

[英]Unity c# control other scripts variables in realtime by registering variable

实时,我想在开始时向我的其他脚本注册一个变量,并希望它由其他脚本实时控制。

公共浮动leftTime;

MyManager.RegisterVariable(leftTime);

就是这样,现在我希望我的经理在更新时自行控制这个变量。 我怎么能做这个?

MyManager中保留 setter 和 getter 函数,然后将它们保存在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);
}

然后,当您调用RegisterVariable时,传递 getter 和 setter。 如果您不打算经常调用它,我建议使用匿名函数。

// in other script

float foobar = 5f;

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

现在您需要将 ptr 返回到包含变量的空间或字典!

public interface IRunningStatistic
{
    /// <summary>
    /// Collects a value
    /// </summary>
    /// <param name="value"></param>
    void Collect(decimal value);

    /// <summary>
    /// The <see cref="IStatisticalFunction"/>'s which are run in the order inserted
    /// </summary>
    IList<IStatisticalFunction> Functions { get; }
}

/// <summary>
/// Represents a function
/// </summary>
public interface IStatisticalFunction
{
    /// <summary>
    /// The <see cref="IRunningStatistic"/> to which this instance belongs
    /// </summary>
    IRunningStatistic Statistic { get; }

    /// <summary>
    /// The name of the function
    /// </summary>
    string Name { get; }

    /// <summary>
    /// A function accepting input
    /// </summary>
    /// <param name="value"></param>
    void Collect(decimal value);

    /// <summary>
    /// Gets all variables by name with their values
    /// </summary>
    /// <returns></returns>
    Dictionary<string, decimal> GetState();

    //SetState / Load

    //Could use an array or dictionary 
}
class InternalFunctionRepresentation : IStatisticalFunction
        {
            public IRunningStatistic Statistic { get; private set; }

            public string Name { get; private set;}

            private readonly Action<decimal> Function;

            public InternalFunctionRepresentation(IRunningStatistic statistic, string name, Action<decimal> function)
            {
                (Statistic, Name, Function) = (statistic, name, function);
            }

            public void Collect(decimal value)
            {
                Function(value);
            }

            public Dictionary<string, decimal> GetState()
            {
    //if i was a byte[] this would be easyer 
                return new Dictionary<string, decimal>() { };
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM