How to check if a particular object in an array has a specific component
I'm trying to get a particular system working that involves collecting all of the collider2D components of a particular layer into an array and the checking each of the collected collider's game object's for particular scripts attached before doing anything meaningful to those objects' scripts.
Here's the code:
void Update()
{
Vector3 parentrotation = Parent.transform.localEulerAngles;
ParentRotationZ = parentrotation.z;
if(HitBoxActive)
{
WithParentHitBoxRotationZ = HitBoxRotationZ + ParentRotationZ;
Collider2D[] TargetsToDamage = Physics2D.OverlapBoxAll(AttackPosition, new Vector2(HitBoxWidth, HitBoxHeight), WithParentHitBoxRotationZ, WhatAreTargets);
if(TargetsToDamage.Length > 0)
{
Debug.Log(TargetsToDamage.Length);
}
for(int i = 0; i < TargetsToDamage.Length; i++)
{
if(TargetsToDamage[i].gameObject.GetComponentInParent<DebugObjectHitDetect>())
{
Debug.Log("Hit");
TargetsToDamage[i].GetComponentInParent<DebugObjectHitDetect>().LastDmgTaken = m_PlayerStatistics.m_BaseDMG;
}
}
}
else
{
HitBoxHeight = 0f;
HitBoxWidth = 0f;
AttackPosition = Vector3.zero;
HitBoxRotationZ = 0;
WithParentHitBoxRotationZ = 0f;
}
}
Yes it is based on this tutorial: https://www.youtube.com/watch?v=1QfxdUpVh5I and if I do manage to make something out of this method then I will be sure to credit it. Anyways, I need to know specifically how to address this component: DebugObjectHitDetect in the objects of the array.
if(TargetsToDamage[i].gameObject.GetComponentInParent<DebugObjectHitDetect>())
arent you already checking it the objects in the array targetstodamage has the component debugobjecthitdetect? i am missing something?
It doesn't appear to do anything if the overlap box is in the collider of the object with DebugObjectHitDetect. It is on the same layer as the layermask WhatAreTargets.
can you try removing the .gameObject from that if? leave it likethis
if(TargetsToDamage[i].GetComponentInParent<DebugObjectHitDetect>())
Your answer
![](https://koobas.hobune.stream/wayback/20220612211225im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I find the largest GameObject in an array? 0 Answers
Array index out of range. But it doesn't appear to be. 2 Answers
How remove/delete/destroy an element from an array by value in c#? 2 Answers
saving user input for later character control 1 Answer
Need help with 3d inventory system 0 Answers