Question

Im trying to understand GetComponent, but Im having a hard time figuring how to write the syntax. I got two scripts ( SpawnBehaviour and SpotClicked) and want to get the bool from "SpawnBehaviour into SpotClicked.

How do I get the syntax right, and change the boolean in SpawnBehaviour to 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;
    }
}

In SpawnBehaviour.cs I have got

public bool stoppedSpawn = false;
Was it helpful?

Solution

Unfortunately the documentation doesn't show you an example in C#, but it's pretty straight forward.

What you'd end up doing is something like

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

There is also the non-generic version

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

but hey, if you can save some keystrokes and casts, why not.

Of course you could cache those components in your Start(), if you're going to access them multiple times anyway. Calling GetComponent is expensive, particularly if you end up doing it every frame for example.

And if you subsequently want to set a boolean variable to true for SpawnBehaviour, you'd do

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

or if you don't care to keep the SpawnBehaviour around, you can do

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

But if you need it anywhere else, or need it often, do cache it.

OTHER TIPS

Conceptually, you should first understand what is a component, and what is a gameobject, then it is not hard to get the syntax right:

enter image description here

For instance:

var layer = someGameObject.GetComponent<GUILayer>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top