Search code examples
c#unity-game-enginegameobject

Unity3D - get component


What is the simplest way to getcomponent in Unity3D C#?

My case:

GameObject gamemaster. 
//C# script MainGameLogic.cs(attached to gamemaster). 
A boolean backfacedisplayed(in MainGameLogic.cs).
A function BackfaceDisplay()(in MainGameLogic.cs).

Another C# script FlipMech.cs, which I need to check from MainGameLogic.cs if(backfacedisplayed == TRUE), I will call BackfaceDisplay()from MainGameLogic.cs. How can I do it in C#?

In js is rather straight forward. In FlipMech.js:

//declare gamemaster
var gamemaster:GameObject;

Then wherever I need:

if(gamemaster.GetComponent(MainGameLogic).backfacedisplayed==true)
{
    gamemaster.GetComponent(MainGameLogic).BackfaceDisplay();
}

But it seems like C# is way more complicated that this.


Solution

  • in c#, you will get the component using this,

    if(gamemaster.GetComponent<MainGameLogic>().backfacedisplayed==true)
        {
            gamemaster.GetComponent<MainGameLogic>().BackfaceDisplay();
        }