[英]Unity2D Raycasting
我正在嘗試編寫一個腳本,當玩家被敵人擊中時將重新加載關卡。 我是gamedev和C#的新手,所以我對代碼沒有100%的信心。
我遇到了一些錯誤,這些錯誤使我無法正常工作,而且我在網上找不到任何指向正確方向的信息。
using UnityEngine;
using System.Collections;
public class RobotAttack : MonoBehaviour
{
void Update()
{
RaycastHit2D hit;
Vector2 attackPosition = transform.position + new Vector2(0f, 1f);
if (Physics2D.Raycast(attackPosition, transform.forward, hit, 1f) && (hit.transform.tag == "Player"))
{
Application.LoadLevel(Application.loadedLevel);
}
}
}
我得到的錯誤如下。
Assets/Scripts/RobotAttack.cs(14,44): error CS0121: The call is ambiguous between the following methods or properties: `UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)' and `UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3)'
Assets/Scripts/RobotAttack.cs(17,66): error CS0165: Use of unassigned local variable `hit'
Assets/Scripts/RobotAttack.cs(17,23): error CS1502: The best overloaded method match for `UnityEngine.Physics2D.Raycast(UnityEngine.Vector2, UnityEngine.Vector2, float, int)' has some invalid arguments
Assets/Scripts/RobotAttack.cs(17,23): error CS1503: Argument `#3' cannot convert `UnityEngine.RaycastHit2D' expression to type `float'
抱歉,如果這是可怕的格式,這是我在本網站的第一篇文章:^)謝謝。
資產/腳本/Robotack.cs(14,44):錯誤CS0121:下列方法或屬性之間的調用不明確:
UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)' and
UnityEngine.Vector3.operator + (UnityEngine.Vector3,UnityEngine.Vector3)'
這意味着存在另一種具有相同名稱的方法,因此編譯器不知道您打算使用哪個方法。 即: Vector2.operator
和Vector3.operator
更改名稱將解決此問題或指定前綴庫。
資產/腳本/RobotAttack.cs(17,66):錯誤CS0165:使用未分配的局部變量“命中”
這很明顯,您沒有將hit
定義為任何內容,僅將其類型定義為。 您可以嘗試: RaycastHit2D hit = new RaycastHit2D();
但是我不確定它的構造函數。
編輯: 審查構造函數后:
資產/腳本/RobotAttack.cs(17,23):錯誤CS1502:“ UnityEngine.Physics2D.Raycast(UnityEngine.Vector2,UnityEngine.Vector2,float,int)”的最佳重載方法匹配具有一些無效參數
資產/腳本/RobotAttack.cs(17,23):錯誤CS1503:參數
#3' cannot convert
UnityEngine.RaycastHit2D表達式#3' cannot convert
為“ float”類型
這僅表示您要傳遞的參數類型錯誤。 值得注意的是,第三個參數並不是float
實際上的,它看起來像您正在傳遞RaycastHit2D
類型的對象。 如果您有信心將其轉換為浮點數,則可以嘗試將其轉換為浮點數,盡管這種可能性很小。 另外,您將需要建立要使用的正確輸入變量。
希望這有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.