Search Unity

GetComponent

Discussion in 'Scripting' started by 2dgamemania, Feb 28, 2015.

  1. 2dgamemania

    2dgamemania

    Joined:
    Apr 30, 2014
    Posts:
    153
    Hi,

    Sorry if this is a basic question but i'm getting confused about when to use getcomponent

    eg

    say i have to objects, a circle and a square, i assigned circle.script to the circle and to access the squares rigidbody id put the following in circle.script (also dragging the square to the gameobject within the inspector)

    var otherGameObject : GameObject;
    otherGameObject.rigidbody.useGravity = false;

    The above works fine but I thought I should have needed to use GetComponent for this? so getting abit confused to when i need to use that?

    Thanks for any help....
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Component.rigidbody is a short cut method for GetComponent<Rigidbody>(). Unity was very inconsistent when choosing where to add these shortcut methods. It's become a bit of a mess. Unity's words, not mine. There is no rhyme or reason to which systems have short cut methods and which don't.

    So to fix this problem all of the shortcut properties are being removed from Unity 5 onwards. Only .transform will remain.

    So for now it makes no difference which you use. But in the future only GetComponent will work. If strongly suggest moving to GetComponent now rather then waiting for Unity 5 to force the issue.
     
    2dgamemania and Napivo like this.
  3. ZO5KmUG6R

    ZO5KmUG6R

    Joined:
    Jul 15, 2010
    Posts:
    490
    Mesh Renderer, Custom components, Lights, etc would require GetComponent. Please note that .renderer, .collider, and other shortcuts have been removed in Unity 5.
     
  4. Napivo

    Napivo

    Joined:
    Feb 9, 2015
    Posts:
    39
    Oh, now I understand why I am having such a hard time with the new UI.

    The penny drops with a very large parachute :)
     
    Kiwasi likes this.
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Namespaces are another thing new in 4.6. As well as the event system. Unity is making a general drive to do things the 'proper' way, as opposed to the Unity way. In general this appeals to coders, but may serve to make the engine as a whole slightly more difficult to get into.
     
  6. 2dgamemania

    2dgamemania

    Joined:
    Apr 30, 2014
    Posts:
    153
    Thanks thats really cleared things up, appreciate that. I will try and use the Getcomponent to get used to using it then. I

    hope they keep unity script as dont really want to go to c# !(even though it might make life easier in the long run) thanks

    again.