2016-03-18 57 views
1

我有一個問題試圖讓我的遊戲編譯,這個問題源於我的損壞接口腳本和我的子彈腳本。控制檯中的錯誤代碼如下。Unity 4.6不能隱式地將'UnityEngine.Component'類型轉換爲'DamageInterface'

Assets/Scripts/Projectile.cs(32,33):error CS0266:無法隱式轉換類型UnityEngine.Component' to DamageInterface'。一個顯式轉換存在(是否缺少強制轉換?)

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)); 
+0

包含RaycastHit的代碼,換言之,它是否實現DamageInterface或碰撞器對象 – Seabizkit

+0

如何看起來我不相信我已經這樣做了,因爲我從統一5移動到統一後必須更改我的代碼4 – Ben411916

+0

這有幫助嗎? http://stackoverflow.com/questions/30020429/raycast-to-get-gameobject-being-hit-to-run-script-and-function-on-gameobject – Seabizkit

回答

2

在Unity5.x您可以獲取組件,接口是這樣的:

IInterface myInterface = gameObject.GetComponent<IInterface>(); 
在舊版本

你需要執行演員:

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

這是因爲GetComponent返回一個Component和你的Interf王牌不是。該錯誤實際上告訴你該怎麼做:

一個顯式轉換存在(是否缺少強制轉換?)

是你失蹤的演員。

+0

感謝現在看起來相對簡單。當我回家並讓你知道時,我會執行它。再次感謝 – Ben411916

+0

並且您不能在舊版Unity中使用帶有接口的通用版本。 – Everts

+0

嗨@Ben411916對TICK提供任何有用的答案非常重要且有幫助,以幫助解決問題。在這個標籤上有一個令人難以置信的數量混亂,這是很難得到解答的問題。歡呼 – Fattie

相關問題