[英]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.