Setting GameObject as target in another script

Hi

I have two scripts, PlayerController.cs and Target.cs in PlayerController there is a public GameObject target;

In Target.cs I want to set the gameobject I click as target in the PlayerController script, but obviously I messed up somewhere.. anyone have a hint?

The first line works just fine as far as I can see. Debug.Log prints out the name of the object I click. I am also able to access target and other int's etc from the PlayerController using pc. so I guess the third line works? However I cant set the target of PlayerController to "go"

Error: NullReferenceException: Object reference not set to an instance of an object

Target.cs

    void OnMouseDown() {
    GameObject go = this.gameObject;
    Debug.Log(go);
    PlayerController pc = (PlayerController)GetComponent("PlayerController");
    pc.target = go;
}

Anyway, thanks for looking

Is your PlayerController script an attached component of the clicked on Target? If not, you will have null returned. The syntax should also be GetComponent<PlayerController>();

Ofcourse.. I have the PlayerController on the player and the Target on the target. no wonder it wont work Guess I have to rewrite the Target script

2 Answers

2

Ah yes, you were on the right track though. Just missing the step of getting a reference to your player, to get it's script component.

void OnMouseDown()
{
   GameObject.Find("ThePlayerObjectsName").GetComponent<PlayerController>().target = gameObject;

   // Or if you have the Player setup with a Tag

   GameObject.FindWithTag("TagName").GetComponent<PlayerController>().target = gameObject;
}

=)

Thank you I got it working now.. now I just need to make "the rest" and I have a completed game ;) should be easy

coulfd you place the whole scripts please ? that wouyd be greatfull

Please don't post comments as answers. Post comments by clicking the [add new comment] button, a window then open for you to type in. Answer fields are for answers only, as this is a knowledge base. You can convert this answer to a comment (or just edit your original question), you'll also get a better chance of getting an actual answer if the main list shows none or one answer in blue =] Under the answer where it says edit | delete | more , click on more , then convert to comment