Access other game objects’ props in Unity using GetComponent( );

Within the first few days of game development, you are bound to reach the point where you’d have to use or change some properties of game objects from other game objects.

To accommodate this, you have to use the method “GetComponent<>( )”.

Always remember that Unity has a hierarchical architecture and hence you need to take a step by step approach when accessing properties.

Let me take a simple example of changing the material color of one cube from the script attached to another cube.

Unity
  • As we are interested to change the color of the material, we are looking at a ladder of transform(root) -> Mesh Renderer -> Material.
  • If we successfully grab the mesh renderer component, we’ll have an access to all public properties and data of the mesh renderer, and material is one of them.

Let's get to Visual Studio to write some code.

I am using the OnCollisionEnter( ) method here. If you have not seen the article on it, please do so before going ahead.

  • First, Let's see how we get the hold of another object. Here, I have tagged the small cube with a tag of “Enemy”. Please note that I am accessing the other cube with an enemy tag from a cube with a player tag.
C#
  • Now, let’s dig the ladder and grab the mesh renderer component.
C#
  • Now, we need to generate random colors so that with each bounce of the object, the material will get a new color.
C#

Next, we have to apply the physics material to the object and set its properties to mimic the rubber physic, and then attach it to the object.

Unity
Unity

That's it. See the result here :)

Unity

In essence, we are accessing the enemy object’s mesh renderer component to change the material color from the player script and our hook was the tag “enemy”.

There are many other ways to get the hooks but the tool will remain the same, GetComponent<>( );

Thank you very much

Work in Progress.