【发布时间】:2019-08-07 22:25:39
【问题描述】:
想让我的球体能够互相伤害
已尝试获取其他对象的组件
健康脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Hitpoints
{
private int health;
public int healthMax;
public Hitpoints(int health)
{
this.health = health;
}
public int GetHealth()
{
return health;
}
public float GetHealthPercent()
{
return (float)health / healthMax;
}
public void Damage(int damageAmount)
{
health -= damageAmount;
if (health < 0)
{
health = 0;
}
}
public void Heal(int healAmount)
{
health += healAmount;
if (health > healthMax)
{
health = healthMax;
}
}
}
伤害脚本
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Detect_Blue : MonoBehaviour
{
Hitpoints hitpoints = new Hitpoints(100);
bool onetime = false;
public float radius;
public Vector3 direction = new Vector3(2, 2, 2);
private void Start()
{
Debug.Log("Health: " + hitpoints.GetHealth());
InvokeRepeating("DetectEnemy", 4f, 2f);
}
private void DetectEnemy()
{
var hitColliders = Physics.OverlapSphere(direction, radius);
for (var i = 0; i < hitColliders.Length; i++)
{
if (hitColliders[i].CompareTag("Player"))
{
if (!onetime)
{
onetime = true;
print(hitColliders[i].tag);
InvokeRepeating("Hello", 1, 1);
}
}
// collect information on the hits here
}
}
private void Hello()
{
var hitColliders = Physics.OverlapSphere(direction, radius);
for (var i = 0; i < hitColliders.Length; i++)
{
if (hitColliders[i].CompareTag("Player"))
{
hitColliders[i].GetComponent<Hitpoints>().Damage(10);
}
Debug.Log("Damaged: " + hitColliders[i].GetComponent<Hitpoints>().GetHealth());
if (hitpoints.GetHealth() == 0)
{
Destroy(gameObject);
}
}
}
}
ArgumentException:GetComponent 要求请求的组件“Hitpoints”派生自 MonoBehaviour 或 Component 或者是一个接口。 UnityEngine.Component.GetComponent[Hitpoints] () (在 C:/buildslave/unity/build/Runtime/Export/Component.bindings.cs:42) Detect_Blue.Hello () (at Assets/Detect_Blue.cs:57)
【问题讨论】:
-
您想知道错误发生的原因或其他处理问题的方法吗?正如错误消息所说,将 MonoBehaviour 接口添加到 Hitpoint.cs。你也可以使用对撞机和 Oncollisionenter 方法来检测碰撞