Pregunta

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.

¿Fue útil?

Solución

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

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

Otros consejos

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<>();
  }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top