[英]Unity 4.6 Cannot implicitly convert type `UnityEngine.Component' to `DamageInterface'
I am having an issue trying to get my game to compile, the issue stems from my damage interface script and my projectile script. 我在尝试编译游戏时遇到问题,该问题源于我的损坏界面脚本和弹丸脚本。 The error code in the console is as follows. 控制台中的错误代码如下。
Assets/Scripts/Projectile.cs(32,33): error CS0266: Cannot implicitly convert type UnityEngine.Component' to
DamageInterface'. 资产/脚本/Projectile.cs(32,33):错误CS0266:无法将类型UnityEngine.Component' to
隐式转换UnityEngine.Component' to
DamageInterface'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)
DamageInterface.cs DamageInterface.cs
using UnityEngine;
using System.Collections;
//damage interface
public interface DamageInterface {
void TakeHit (float damage, RaycastHit hit);
}
Projectile.cs 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
}
}
I believe I have used the typeof(T) approach to get my interface component but I must be missing something clearly. 我相信我已经使用typeof(T)方法来获取接口组件,但是我必须清楚地缺少一些东西。 Thanks 谢谢
The error resides on this line in my Projectile.cs: 错误驻留在我的Projectile.cs的这一行上:
DamageInterface damageableObject = hit.collider.GetComponent(typeof(DamageInterface));
In Unity5.x you can fetch component that are interfaces like this: 在Unity5.x中,您可以获取如下接口的组件:
IInterface myInterface = gameObject.GetComponent<IInterface>();
in older version you need to perform a cast: 在旧版本中,您需要执行强制转换:
IInterface myInterface = (IInterface)gameObject.GetComponent(typeof(IInterface));
this is because GetComponent returns a Component and your interface is not. 这是因为GetComponent返回一个Component而您的接口却没有。 The error actually tells you what to do: 该错误实际上告诉您该怎么做:
An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)
Yes you were missing the cast. 是的,您缺少演员表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.