GetComponent noob fail

I’m almost embarrassed to ask this, since it is so basic, but it seems as if I’m missing something fundamental here so I thought I’d ask.

I have not been able to reference a script dynamically. For example:

function OnMouseDown(){

transform.Find("Player").GetComponent(PlayerController).target = transform;

}

Yields,

NullReferenceException
EnemyController.OnMouseDown () (at Assets\Scripts\Controllers\EnemyController.js:7)
UnityEngine.GameObject:SendMessage(String, Object, SendMessageOptions)
UnityEngine.GameObject:SendMessage(String, Object, SendMessageOptions)
UnityEngine.MouseOverPair:SendMessage(String)
UnityEngine.SendMouseEvents:smile:oSendMouseEvents()

Basically, I always get a NullReferenceException when using GetComponent. What am I doing wrong

I’m not sure, but here are some thoughts.

“transform.Find” locates a child. “gameObject.Find” locates another game object. The way it’s written, I think “Player” has to be a child of the object this script is attached to.

I searched for “PlayerController” in the Unity Script Reference and came back with nothing. Do you mean CharacterController?

If you have a script named “PlayerController”, it needs to have a variable named “target”. (I didn’t see a CharacterController.target property.)

(These responses may be ridiculous. It’s first thing Monday morning.)

As you say,PlayerController is my own script possessing variable “target”.

Replacing transform.Find with gameObject.Find fixed the problem.

Seems important to know, so thanks!

Yeah, I’m glad you replied. Someone else will have this same problem, so it’s great to know the solution!