Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以相同的方式处理多个组件_C#_Unity3d - Fatal编程技术网

C# 以相同的方式处理多个组件

C# 以相同的方式处理多个组件,c#,unity3d,C#,Unity3d,我有一个Unity类,它可以有多种类型的组件。我想以一种预定义的方式来处理这些组件->这意味着:我心里有一个方法体,我不想为不同的组件更改它 但由于接口不能有方法体,我不能在同一个类中使用多个接口,它们以相似的方式工作,但根据它们的组件不同 我知道我实际上是在谈论C语言中的多重继承,但是有没有一种方法可以在unity engine中实现这种概念呢 我想要这样的东西 public interface IProcessableComponent<T> where T : Componen

我有一个Unity类,它可以有多种类型的组件。我想以一种预定义的方式来处理这些组件->这意味着:我心里有一个方法体,我不想为不同的组件更改它

但由于接口不能有方法体,我不能在同一个类中使用多个接口,它们以相似的方式工作,但根据它们的组件不同

我知道我实际上是在谈论C语言中的多重继承,但是有没有一种方法可以在unity engine中实现这种概念呢

我想要这样的东西

public interface IProcessableComponent<T> where T : Component
{
    void Process();
}

public class ProcessableComponentsBase : IProcessableComponent<Rigidbody>, IProcessableComponent<Collider2D>
{
    public void Process()
    {

    }
}

而不是流程有一个可以在实现中更改的主体。我希望这种行为保持不变。

如果我理解正确,您需要这样的东西:

public interface IProcessableComponent
{
    void Process(Vector3 position);
}

public abstract class ProcessableComponentBase : MonoBehaviour, IProcessableComponent
{
    [SerializeField]
    private Vector3 holdedVector;
    public Vector3 HoldedVector { get { return holdedVector; } protected set { holdedVector = value; } }
    public virtual void Process(Vector3 newVector)
    {
        HoldedVector = newVector;
    }
}

public class ComponentA : ProcessableComponentBase
{
}

public class ComponentB : ProcessableComponentBase
{
}

public class TestComponentProcessing : MonoBehaviour
{
    private void Awake()
    {
        var components = GetComponents<IProcessableComponent>();

        foreach(var entry in components)
        {
            entry.Process(Vector3.zero);
        }
    }
}

如果你显示你想做什么,我可以编辑我的答案。

你能显示一些代码吗?我不清楚你想要什么。也许你想用泛型?但是很明显,需要一些伪代码来让你的意图更清晰。让我用一个代码片段来更新这篇文章。你想对组件做什么?您希望如何调用流程方法?