Search Unity

transform.parent.GetComponent executing error?

Discussion in 'Scripting' started by Kovenant, Sep 30, 2014.

  1. Kovenant

    Kovenant

    Joined:
    Sep 18, 2013
    Posts:
    254
    Hi all..

    I'm trying to get these lines of codes to work but I'm getting an error message saying:
    "NullReferenceException: Object reference not set to an instance of an object"

    Code (JavaScript):
    1. function Awake()
    2. {
    3.     parentLastPos = transform.parent.position;
    4.     Debug.Log("Parent Last Position: " + parentLastPos);
    5. }
    6.  
    7. function Update()
    8. {
    9.     if(transform.GetComponentInParent(PlayerMovement).grounded)
    10.     {
    11.         headbobStepCounter += Vector3.Distance(parentLastPos, transform.parent.positiion) * headbobSpeed;
    12.     }
    I don't know how to solve it.. I have a script on the parent object called PlayerMovement and I'm trying to access it.... :(
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Are you sure?

    Code (csharp):
    1. function Start () {
    2.     if (GetComponentInParent (PlayerMovement))
    3.         Debug.Log ("Has component");
    4.     else
    5.         Debug.Log ("Nope");
    6. }
    --Eric
     
    Kovenant likes this.
  3. Kovenant

    Kovenant

    Joined:
    Sep 18, 2013
    Posts:
    254
    I changed transfom.GetComponentInParent to only GetComponentInParent and it worked just fine... :)
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Hmm, should be the same either way; the transform part is unnecessary but shouldn't change anything.

    --Eric
     
  5. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    It may also be a good manner to get the reference to the component once and do all the other stuff with it instead of calling GetComponent all the time in update. I'm not quite sure how big the overhead of the generic version in JS/US is, but it will at least simplify the code if you plan to add more code to the script and need to access it again.
     
    Kovenant likes this.