【问题标题】:Unity 4.6 Cannot implicitly convert type `UnityEngine.Component' to `DamageInterface'Unity 4.6 无法将类型“UnityEngine.Component”隐式转换为“DamageInterface”
【发布时间】:2016-03-18 22:07:25
【问题描述】:

我在尝试编译我的游戏时遇到问题,该问题源于我的损坏界面脚本和我的射弹脚本。控制台中的错误代码如下。

Assets/Scripts/Projectile.cs(32,33):错误 CS0266:无法隐式转换类型 UnityEngine.Component' toDamageInterface'。存在显式转换(您是否缺少演员表?)

DamageInterface.cs

using UnityEngine;
using System.Collections;
//damage interface

public interface DamageInterface {

    void TakeHit (float damage, RaycastHit hit);

}

Projectile.cs

using UnityEngine;
using System.Collections;

public class Projectile : MonoBehaviour {

    public LayerMask collisionMask; //detect what layer projectile collides with 
    float speed = 10;
    float damage = 1;

    public void SetSpeed(float newSpeed) {
        speed = newSpeed;
    }

    void Update () {
        float moveDistance = speed * Time.deltaTime;
        CheckCollisions (moveDistance);
        transform.Translate (Vector3.forward * moveDistance);
    }


    void CheckCollisions(float moveDistance) { //raycast to detect collision
        Ray ray = new Ray (transform.position, transform.forward);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, moveDistance, collisionMask)) {
            OnHitObject(hit);
        }
    }


    void OnHitObject(RaycastHit hit) {
        DamageInterface damageableObject = hit.collider.GetComponent(typeof(DamageInterface)); //ERROR RESIDES HERE
        if (damageableObject != null) {
            damageableObject.TakeHit(damage, hit); //damage + raycast hit
        }
        GameObject.Destroy (gameObject); //destroy projectile if enemy layer is hit
    } 
}

我相信我已经使用 typeof(T) 方法来获取我的界面组件,但我必须清楚地遗漏一些东西。谢谢

错误位于我的 Projectile.cs 中的这一行:

DamageInterface damageableObject = hit.collider.GetComponent(typeof(DamageInterface));

【问题讨论】:

  • 包含 RaycastHit 的代码,换句话说,它是否实现了 DamageInterface 或对撞机对象
  • 我不相信我已经这样做了,因为在从统一 5 移动到统一 4 后我不得不更改我的代码
  • DamageInterface 不扩展行为或组件。
  • 这与我最初在 unity 5 中编译时的方式相似,以前的版本不获取与我的问题所在的函数的接口

标签: c# unity3d


【解决方案1】:

在 Unity5.x 中,您可以获取如下接口的组件:

IInterface myInterface = gameObject.GetComponent<IInterface>();

在旧版本中,您需要执行强制转换:

 IInterface myInterface = (IInterface)gameObject.GetComponent(typeof(IInterface));

这是因为 GetComponent 返回一个 Component 而你的界面不是。错误实际上告诉你该怎么做:

存在显式转换(您是否缺少强制转换?)

是的,你错过了演员表。

【讨论】:

  • 感谢现在似乎相对简单。我回家后会实施它并告诉你。再次感谢
  • 而且你不能在旧的 Unity 中使用带有接口的通用版本。
  • 嗨@Ben411916 勾选任何有用的答案非常重要且有帮助,以帮助解决问题。 SO上的这个标签中有大量的混乱,很难回答问题。欢呼
  • @Everts 嘿,你知道如何转换这个“IInterface myInterface = gameObject.GetComponent();”放入 if 语句的布尔值,表示 if gameobject.getcomponent() return true
  • 你可以像下面这样: public static bool IsComponentAvailable(this GameObject obj, ref T t){ t = obj.GetComponent(); return t != null;} 然后你使用 if(gameObject.IsComponentAvailable(ref interfaceRef) == true){}
猜你喜欢
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多