Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question GetComponentInParent gets component on itself instead

Discussion in 'Scripting' started by kader1081, Mar 11, 2023.

  1. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    365
    Hi I'm trying to acces a script called coreProperties on parent but object that trying to acces that also has that component and it accesses on itself.
    Code (CSharp):
    1. public class Core_5 : MonoBehaviour
    2. {
    3.     public GameObject projectile;
    4.     AudioSource source;
    5.     public AudioClip mp5sound;
    6.  
    7.     FindClosestEnemy getClosestEnemy;
    8.  
    9.  
    10.  
    11.     public float soundVolume;
    12.  
    13.     float bulletSpeed = 5f;
    14.  
    15.     public float bulletDamage;
    16.  
    17.     coreProperties coreProperties;
    18.  
    19.     float range = 3f;
    20.  
    21.     Vector2 direction = new Vector2(5, 5);
    22.  
    23.     public float time = 0.7f;
    24.  
    25.     float getTime;
    26.     GameObject hero;
    27.  
    28.  
    29.  
    30.  
    31.     bool timeb;
    32.     void Start()
    33.     {
    34.         coreProperties = GetComponentInParent<coreProperties>();
    35.  
    36.  
    37.         hero = GameObject.Find("Hero");
    38.  
    39.         getClosestEnemy = hero.GetComponentInParent<FindClosestEnemy>();
    40.         source = GetComponent<AudioSource>();
    41.  
    42.     }
    43.  
    44.     // Update is called once per frame
    45.     void Update()
    46.     {
    47.         if (WeaponCharacterChoice.timescal != 0f)
    48.         {
    49.  
    50.             timer();
    51.  
    52.             if (timeb)
    53.             {
    54.                 timeb = false;
    55.                 getTime = TimeModifier();
    56.  
    57.  
    58.  
    59.  
    60.  
    61.                 Debug.Log(coreProperties.coolDown+ coreProperties.gameObject.name);
    62.                 shoot();
    63.             }
    64.  
    65.         }
    66.  
    67.     }
    68.  
    69.  
    70.     /*  void turn()
    71.       {
    72.  
    73.           float x = Input.GetAxis("Horizontal");
    74.           if (x < 0) transform.localScale = new Vector3(1, -1, 1);
    75.           else if (x > 0) transform.localScale = new Vector3(1, 1, 1);
    76.           if (getClosestEnemy.closestEnemy() != null) direction = getClosestEnemy.closestEnemy().transform.position - transform.position;
    77.  
    78.  
    79.  
    80.  
    81.           float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    82.           transform.rotation = Quaternion.Euler(0, 0, angle);
    83.  
    84.  
    85.       }
    86.     */
    87.     void shoot()
    88.     {
    89.  
    90.         if (getClosestEnemy.closestEnemy() != null) direction = getClosestEnemy.closestEnemy().transform.position - transform.position;
    91.         else direction = new Vector2(200, 200);
    92.         if (direction.magnitude <= range)
    93.         {
    94.             float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    95.             transform.parent.rotation = Quaternion.Euler(0, 0, angle);
    96.             source.PlayOneShot(mp5sound, soundVolume);
    97.  
    98.  
    99.             GameObject bullet = Instantiate(projectile, transform.position, transform.rotation);
    100.  
    101.             bullet.GetComponent<Rigidbody2D>().velocity = direction.normalized * bulletSpeed*0.3f;
    102.  
    103.             bullet.GetComponent<Bullet_5>().damage = DamageModifier();
    104.  
    105.         }
    106.  
    107.     }
    108.  
    109.     void timer()
    110.     {
    111.  
    112.         if (!timeb)
    113.         {
    114.             getTime -= Time.deltaTime;
    115.  
    116.         }
    117.         if (getTime <= 0) timeb = true;
    118.  
    119.     }
    120.  
    121.     float TimeModifier()
    122.     {
    123.  
    124.         float timer = time - (time * (CharacterStats.attackSpeed / 100 + coreProperties.coolDown / 100 - 2));
    125.  
    126.         return timer;
    127.  
    128.     }
    129.     float DamageModifier()
    130.     {
    131.  
    132.  
    133.         float damage = bulletDamage + (bulletDamage * coreProperties.damage * ExperienceBar.Level / 2);
    134.  
    135.         return damage;
    136.  
    137.     }
    138.  
    View attachment 1210815 View attachment 1210815 View attachment 1210815
     
  2. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    656
    Theres a few ways to handle these situations.

    Is the 'parent' you want the script from, the top most root object?

    If so, you can always access the transform.root.GetComponent<>

    If not, though a little less performant, you can get all the scripts of that type up the chain, with GetComponentsInParent<>, and then identify by name, id , etc.
     
  3. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    365
    I solved with transform.parent.getcomponent is that a bug or something
     
  4. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    656
    Im unsure what you mean, but what you did is not a bug. You just access the transforms parent. Fair enough. If it works, it works. :D
     
  5. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    365
    No I mean I was using GetComponentInparent but ıt gets the component on itself instead of on parent
     
  6. Chubzdoomer

    Chubzdoomer

    Joined:
    Sep 27, 2014
    Posts:
    107
    From the official documentation:
     
    Bunny83, Kurt-Dekker and kader1081 like this.
  7. Sledzislaw

    Sledzislaw

    Joined:
    Dec 7, 2021
    Posts:
    3
    I'ts not bug - it's feature :D At least according to documentation, as it says:
    I've found it also a bit confusing (regarding the method name) while trying to access component InParent(!).
    But solution is as easy as You've already concluded: start searching from
    Code (CSharp):
    1. myGameObject.transform.parent.GetComponentInParent<T>()
     
  8. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,135
    It would also be possible to add an extension method that allows skipping the game object from which the search is initiated:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public static class ComponentExtensions
    4. {
    5.     public static T GetComponentInParents<T>(this Component component, Self self, Inactive inactive) where T : class
    6.     => self switch
    7.     {
    8.         Self.Include => component.GetComponentInParent<T>(inactive == Inactive.Include),
    9.         _ when component.transform.parent is Transform parent && parent != null => parent.GetComponentInParent<T>(inactive == Inactive.Include),
    10.         _ => null
    11.     };
    12.  
    13.     public static T GetComponentInParents<T>(this Component component, Self self) where T : class
    14.         => component.GetComponentInParents<T>(self, component.gameObject.activeInHierarchy ? Inactive.Exclude : Inactive.Include);
    15. }
    16.  
    17. public enum Self { Exclude, Include }
    18. public enum Inactive { Exclude, Include }
    Usage example:
    Code (CSharp):
    1. var parentTransform = component.GetComponentInParents<Transform>(Self.Exclude);

    Or for even more control over which game objects in the parent chain are searched:
    Code (CSharp):
    1. public static T GetComponentInParents<T>(this Component component, Range range) where T : class
    2. {
    3.     Transform transform = component.transform;
    4.     for(int i = 0; i <= range.End.Value; i++)
    5.     {
    6.         if(i >= range.Start.Value && transform.TryGetComponent(out T result))
    7.         {
    8.             return result;
    9.         }
    10.  
    11.         transform = transform.parent;
    12.         if(transform == null)
    13.         {
    14.             break;
    15.         }
    16.     }
    17.  
    18.     return null;
    19. }
    Usage example:
    Code (CSharp):
    1. var parentCollider = component.GetComponentInParents<Collider>(1..1);
     
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Just remember that this code:

    ... will crash every time you run it on a GameObject without a parent.

    Please don't necro-post. If you have a new question, make a new post. It's FREE!!