相关疑难解决方法(0)

Unity中的简单事件系统

我试图在Unity中使用事件系统(C#方式),但我遇到了实现它的问题.

大多数示例都显示了一个类,您可以在其中定义处理程序; 然后你在相同的类中编写,匹配处理程序签名的函数,并将事件写为静态

public class EventExample : MonoBehaviour
{
    public delegate void ExampleEventHandler();
    public static event ExampleEventHandler OneDayPassed;

    public static void NextTurn()
    {
        // do stuff then send event
        if (OneDayPassed != null)
            OneDayPassed();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在另一个类中,您订阅事件,创建一个实际执行某些操作的函数

public class EntityWatcher: MonoBehaviour
{
    void Start()
    {
        EventExample.OneDayPassed += this.PrepareNextDay;
    }

    public void PrepareNextDay()
    {
        // Do other stuff that happen after the day is done

    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止没有任何问题,但我不知道如何设计这个,所以任何特定类型的GameObject都会订阅此事件.例如,如果你有一个GO的员工类别,那就是工作8到6,你在运行时实例化它们; 我应该订阅这个类别的主类,还是应该创建一个附加到游戏对象预制件的脚本,订阅该事件?

目标是所有应该在体育中心进行8到6班的工作人员,知道"完成日期"事件何时启动,但我不想订阅我实例化的每一个预制件.

根据我的理解,我应该在预制件上添加一个带有所需代码的脚本,但我找不到一个实际的例子来说明这是否实际上是这样做的.

c# events unity-game-engine

5
推荐指数
1
解决办法
3万
查看次数

扩展方法如何工作?

我想在Unity3d中为Vector3类创建一个扩展方法.但我似乎没有得到它.这就是我所拥有的:

public static class ExtensionMethods{

    public static Vector3 MaxValue(this Vector3 _vec3)
    {
        return new Vector3(float.MaxValue,float.MaxValue,float.MaxValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想打一个Vector3.MaxValue,就像float.MaxValue用这行代码:

Vector3 closestPoint = Vector3.MaxValue;
Run Code Online (Sandbox Code Playgroud)

但后来我得到了这个错误:

error CS0117: `UnityEngine.Vector3' does not contain a definition for `MaxValue'
Run Code Online (Sandbox Code Playgroud)

我知道这会奏效:

Vector3 closestPoint = new Vector3().MaxValue();
Run Code Online (Sandbox Code Playgroud)

但后来我创建了2个新Vector3实例.一个在MaxValue通话中,一个在外面.是不是可以只使用这种代码制作一个并执行此操作:

Vector3 closestPoint = Vector3.MaxValue;
Run Code Online (Sandbox Code Playgroud)

c# extension-methods unity-game-engine

0
推荐指数
1
解决办法
1006
查看次数

标签 统计

c# ×2

unity-game-engine ×2

events ×1

extension-methods ×1