[英]Unity Sword Collision Attack
嘿伙計們,我想做一個劍攻擊。 但我得到以下錯誤:
NullReferenceException:Object 引用未設置為 object 的實例
這些是我的代碼: 我的武器攻擊腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weaponattack : MonoBehaviour
{
Enemy Enemy;
public float power;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnTriggerEnter(Collider col)
{
if(col.tag == "Enemy")
{
var kılıc = GetComponent<Enemy>();
Enemy.currentHealt -= 10;
Enemy.TakeDamage();
Debug.Log("Düşman Vuruldu");
}
}
}
這是我的敵人健康腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public float currentHealt;
public float maxHealth;
// Use this for initialization
void Start () {
currentHealt = maxHealth;
}
// Update is called once per frame
void Update () {
}
public void TakeDamage()
{
currentHealt -= 10;
if(currentHealt < 0)
{
die();
}
}
void die()
{
Destroy(gameObject);
}
}
你能告訴他們嗎?我不明白為什么這些代碼不起作用,為什么我會收到這個錯誤。
我認為你的問題出在這一行GetComponent<Enemy>();
這需要一個游戲object來獲取組件
Enemy = col.GetComponent<Enemy>();
應該是你在做什么
您也可能無法將變量 Enemy 稱為與您的 class 敵人完全相同的問題,我會將其更改為Enemy enemy;
和
enemy = col.GetComponent<Enemy>();
分別
這似乎很簡單。 您沒有將 Enemy 分配給 Weaponattack,因此當您第一次引用 Enemy ( Enemy.currentHealt
) 時,它會令人討厭。 將 Enemy 設為 public 或 SerializedField 以便您可以在 Inspector 中分配它,或者您想讓 Enemy 進入 Weaponattack。
也不要將您的屬性命名為與您的腳本相同的名稱( Enemy Enemy
)。 很驚訝你沒有收到編譯錯誤。
編輯根據評論:
Enemy enemy;
public void OnTriggerEnter(Collider col)
{
if(col.tag == "Enemy")
{
var kılıc = GetComponent<Enemy>();
kilic.currentHealt -= 10;
kilic.TakeDamage();
Debug.Log("Düşman Vuruldu");
}
}
這也假設您有一個Enemy
附加到您的 Weaponattack ( GetComponent
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.