Unity3d, can't call Script from another script using GetComponent via string

I try to call a function from a gameobject script, from another gameobject script, but I need it to be using strings but when I try to do this

GameObject.Find("Player").GetComponent("myscript").myfunction= false;

unity gives me the following error before I can run

Assets\GenericActor.cs(94,40): error CS1061: 'Component' does not contain a definition for 'myfunction' and no accessible extension method 'myfunction' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?)

Upvotes: 1

Views: 51

Answers (1)

Brandon Bravos
Brandon Bravos

Reputation: 430

Try:

MyScript playerScript = GameObject.Find("Player").GetComponent<MyScript>().myfunction = false;

It could also be done with a tag:

MyScript playerScript = GameObject.FindGameObjectWithTag("Player").GetComponent<MyScript>().myfunction = false;

also, if you're calling a function like void MyFunction(bool myBool) you'd use

MyScript playerScript = GameObject.FindGameObjectWithTag("Player").GetComponent<MyScript>().MyFunction(false);

Upvotes: 1

Related Questions