【发布时间】:2022-01-15 15:25:15
【问题描述】:
有一个手榴弹爆炸和作用范围内物体破坏的代码。由于某种原因,foreach 代码看不到GetComponent<Test>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grenadde : MonoBehaviour {
public float delay = 3f;
public float radius = 50f;
public float force = 700f;
public GameObject explosionEffect;
public GameObject explosionAudio;
float countdown;
public bool isGrabbed = false;
public void Explode() {
StartCoroutine(ExplodeWithTimer(3f));
}
public IEnumerator ExplodeWithTimer(float seconds) {
yield return new WaitForSeconds(seconds);
Instantiate(explosionEffect, transform.position, transform.rotation);
//Collider[] overlappedColliders = Physics.OverlapSphere(transform.position, radius);
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearbyObject in colliders)
{
Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
if (rb != null) {
rb.AddExplosionForce(force, transform.position, radius);
Debug.Log(nearbyObject.name);
}
Test test = nearbyObject.GetComponent<Test>();
if (test != null) {
Debug.Log("PlayerHp");
}
}
Destroy(gameObject);
}
//}
void OnDrawGizmosSelected() {
// Draw a yellow sphere at the transform's position
Gizmos.color = new Color(1, 0, 0, .2f);
Gizmos.DrawSphere(transform.position, radius);
}
}
【问题讨论】:
-
您能否提供更完整的minimal reproducible example 以及您收到的完整错误消息?您确定不想改用
nearbyObject.attachedRigidbody吗? -
does not see是什么意思?该组件是否在您碰撞的对象上? -
请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。