简体   繁体   English

将接口实现作为组件添加到游戏对象

[英]Add interface implementation as a component to a gameobject

Using dependency injection, you can have one same interfaces representing diferent classes, as the class implementation can be bound to the dependency container as per defined at the binding stage of the binding phase.使用依赖注入,您可以拥有一个表示不同类的相同接口,因为 class 实现可以按照绑定阶段的绑定阶段定义的方式绑定到依赖容器。 My question is, once your respective bindings are done, if the implementations are monobehaviour, if there is a chance to add the interface as a component to a gameobject.我的问题是,一旦完成各自的绑定,如果实现是单一行为,是否有机会将接口作为组件添加到游戏对象。

The story of why I would like to do that is pretty long, so it can be assumed that the necesity just came up:).我为什么要这样做的故事很长,所以可以假设刚刚出现了必要性:)。

Find some pseudoCode for a better understanding:查找一些伪代码以便更好地理解:

public interface IFoo {
    //...
}

public class FooIplementtation1: MonoBehaviour {
    //....
}

public class FooIplementtation2: MonoBehaviour {
    //....
}

if (someCondition) {
    Container.Bind<IFoo >().To<FooIplementtation1>();
} else {
    Container.Bind<IFoo >().To<FooIplementtation2>()
}

What I intend to do is:我打算做的是:

//Error. Interface type cannot be added as component.
someTransform.gameObject.AddComponent<IFoo>();

But I get the error:但我得到了错误:

The type IFoo cannot be used as type parameter 'T' in the generic or method GameObject.AddComponent<T>(). IFoo 类型不能用作泛型或方法 GameObject.AddComponent<T>() 中的类型参数“T”。

The method signature is:方法签名是:

public T AddComponent<T>() where T : Component;

Si I tried to make my interface inherit from Monobehaviour and form Component but that did not work. Si 我试图让我的界面从Monobehaviour继承并形成Component但这不起作用。

Any idea if this is possible and if so, how?知道这是否可行,如果可以,怎么办?

GameObject.AddComponent documentation states GameObject.AddComponent文档状态

Adds a component class named className to the game object.将名为 className 的组件 class 添加到游戏 object。

Component type should be class, it can't be struct nor interface.组件类型应该是 class,它不能是结构也不能是接口。 Interfaces are just a contract that states, class has to implement given interface functions and properties.接口只是一个约定,class 必须实现给定的接口函数和属性。 You are hiding why you are using interface for your code but if it is possible create a base class that contains everything that all classes share same.您隐藏了为什么要为代码使用接口,但如果可以创建一个基本 class 包含所有类共享的所有内容。 In short use Polymorphism .总之使用多态 Inherit the base class from monobehaviour and you can do what you want to achieve.从 monobehaviour 继承基础 class ,你可以做你想做的事。

Also think like that interfaces have no data at all.还认为接口根本没有数据。 They are just empty implementation, what part of it can be a component for an object?它们只是空的实现,它的哪一部分可以成为 object 的组件? They just make coding easier nothing else.他们只是让编码更容易而已。 Maybe, you want to look at to the C# Design Patterns .也许,您想查看C# 设计模式

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

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