Search Unity

Best practices RayCast on child/parent collider, Check if contains script.

Discussion in 'Physics' started by mikeNspired, Nov 14, 2016.

  1. mikeNspired

    mikeNspired

    Joined:
    Jan 13, 2016
    Posts:
    82
    -----------EDIT-----------
    I dont even quite understand what im asking for 3 years ago....
    But what I would tell my self from 3 years ago is to have a RigidBody on the class with the scripts.
    For raycasys, colliders, and triggers always follow and maintain this practice. The rigid body has the scripts. In doing so, you can always do, hit.GetComponent<Collider>().attachedRigidBody, then have access to scripts and know exactly which object you are getting.

    -----------END-----------
    What are the best practices for rayCasting. Is their documentation to read about it?

    My problem is when I ray cast an object with multiple children, I may hit the parent collider or the child collider, while the Script is only on the parent.

    I check if(GetComponent<SomeGenericBaseClass>()) on the object and parents to determine if its of the correct object to active events.

    The only way for me to do that is to do something along the lines of

    Code (CSharp):
    1.  if(hit.transform.GetComponent<SomeGenericBaseClass>()){
    2.  
    3.        hit.transform.GetComponent<SomeGenericBaseClass>().ActivateEventB();
    4. }
    5. else if(hit.transform.GetComponentInParent<SomeGenericBaseClass>()){
    6.    
    7.        hit.transform.GetComponent<SomeGenericBaseClass>().ActivateEventB();
    8. }
    I have this problem because of modular 3d models sometimes have to be pieced together for animations such as doors, knobs .etc

    What are you guys doing instead of this, and do you have better ways?
     
    Last edited: Jun 17, 2019
  2. Diesign

    Diesign

    Joined:
    May 15, 2016
    Posts:
    16
    sorry for the necrobump - also very interested
     
  3. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    if the attached collider has a rigidbody, hit.rigidbody with return the rigidbody regardless of the collider hits, this is often what I use in cases like this, seeing as the script and the rigidbody are both on the "parent".

    you can always go transform.root, but that will only work if your wanted parent object is the actual root object (highest up the chain)
     
    mikeNspired likes this.