5

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.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
sooon
  • 4,718
  • 8
  • 63
  • 116

2 Answers2

7

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

if(gamemaster.GetComponent<MainGameLogic>().backfacedisplayed==true)
    {
        gamemaster.GetComponent<MainGameLogic>().BackfaceDisplay();
    }
Nick
  • 1,035
  • 1
  • 11
  • 18
  • I tried your method and get this `error CS0122: 'MainGameLogic.backfacedisplayed' is inaccessible due to its protection level `. – sooon Jan 24 '14 at 08:58
  • 1
    your variables should be public to use in GetComponent() Declare backfacedisplayed as public. – Nick Jan 24 '14 at 08:59
  • I think it works. the error goes away but I still yet to test fully. – sooon Jan 24 '14 at 14:07
1

Nick's answer didn't work for me when I countered this same problem. The script involved an Unity3d asset store that has its own namespace. When I put the class in the namespace, it started working.

using UnityEngine;
using System.Collections;
using Devdog.InventorySystem;

namespace Devdog.InventorySystem.Demo
{
  public class changeStat : MonoBehaviour {
    // ... rest of the code including the gameObject.GetComponent<>();
  }
}
Community
  • 1
  • 1
ShivaFooL
  • 11
  • 2