Skip to main content
 首页 » 编程设计

c#之如何使用 GetComponent 语法

2024年02月13日14qq78292959

我试图理解 GetComponent,但我很难弄清楚如何编写语法。我有两个脚本(SpawnBehaviour 和 SpotClicked)并想从“SpawnBehaviour 到 SpotClicked”中获取 bool 值。

如何获得正确的语法,并将 SpawnBehaviour 中的 bool 值更改为 true?

void OnMouseDown() 
{ 
      screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); 
      offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)); 
 
    if(this.gameObject.tag == "fishSpot"){ 
          Debug.Log("Clicked "+gameObject.name); 
          //get "stopped"bool from "SpawnBehaviour" script and set it to true 
          SpawnBehaviour sb = spawnPoint.GetComponent<SpawnBehaviour>().stoppedSpawn=true; 
    } 
} 

在 SpawnBehaviour.cs 我有

public bool stoppedSpawn = false; 

请您参考如下方法:

不幸的是the documentation没有向您展示 C# 中的示例,但它非常简单。

你最终会做的事情是这样的

SpawnBehavior sb = gameObject.GetComponent<SpawnBehaviour>(); 
SpotClicked sc = gameObject.GetComponent<SpotClicked>(); 
//Do whatever you want with the variables from either MonoBehaviour 

还有the non-generic version

SpawnBehaviour sb = (SpawnBehaviour) gameObject.GetComponent(typeof(SpawnBehaviour)); 

但是,嘿,如果您可以节省一些击键和转换,为什么不呢。

当然,如果您要多次访问它们,您可以将这些组件缓存在 Start() 中。调用 GetComponent 的开销很大,尤其是当您最终在每一帧都执行它时。

如果您随后想为 SpawnBehaviour 设置一个 bool 变量为 true,您可以这样做

SpawnBehaviour sb = gameObject.GetComponent<SpawnBehaviour>(); 
sb.stoppedSpawn = true; 

或者如果您不想保留 SpawnBehaviour,您可以这样做

gameObject.GetComponent<SpawnBehaviour>().stoppedSpawn = true; 

但是如果您在其他地方需要它,或者经常需要它,请缓存它。