O'Reilly logo

Mastering Unity 2D Game Development - Second Edition by Simon Jackson, Ashley Godbold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Coding with components

Components in Unity are the building blocks of any game; almost everything you will use or apply will end up as a Component on a GameObject in a scene. When a GameObject is selected, you can view each of its Components from its Inspector.

You will find that you need to access these various components with script. Next we will discuss the various ways on which you can do this.

Accessing components

To reference the components of a GameObject from within your code, you need to use the GetComponent function. The following shows you examples of how this is achieved:

Rigidbody myScriptRigidBody; void Awake() { var renderer = this.GetComponent<Renderer>(); var collider = renderer.GetComponent<Collider>(); myScriptRigidBody = collider.GetComponent<Rigidbody>(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required