【问题标题】:Why does the foreach code not see GetComponent<>?为什么 foreach 代码看不到 GetComponent<>?
【发布时间】:2022-01-15 15:25:15
【问题描述】:

有一个手榴弹爆炸和作用范围内物体破坏的代码。由于某种原因,foreach 代码看不到GetComponent&lt;Test&gt;

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

标签: c# unity3d


【解决方案1】:

您正在尝试从对撞机中获取组件,而您需要在 GameObject 上使用 GetComponent 而不是在对撞机本身上。这可以通过以下方式实现:

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.gameObject.GetComponent<Test>();
        if (test != null) {                                   
            Debug.Log("PlayerHp");
    }
}

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 2021-02-14
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2021-04-09
    • 2014-10-02
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多