Finding Transfroms like GameObjects

Alright, I’m trying to sort out my codebase. I don’t want my spawners to have to instantiate enemies from inside the game world just because they need references to the player.

What I want is some way to do something like GameObject.Find for a Transform instead. I just need a way to look up a Transform by name and use it later for the target of a lookat script.

Anyone know how to swing this?

private var target : Transform;
var damping = 6.0;
var smooth = true;

function Awake(){
	target = GameObject.Find("Player"); // <---- this guy here doesn't cast to Transform. 
}

function LateUpdate () {
	if (target) {
		if (smooth)
		{
			// Look at and dampen the rotation
			var rotation = Quaternion.LookRotation(target.position - transform.position);
			transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
		}
		else
		{
			// Just lookat
		    transform.LookAt(target);
		}
	}
}

function Start () {
	// Make the rigid body not change rotation
   	if (rigidbody)
		rigidbody.freezeRotation = true;
}
	target = GameObject.Find("Player").transform;

–Eric

Thanks, Eric!

Unfortunately, when I try it that way I get the following error:

NullReferenceException
LookAtPlayer.Awake ()   (at Assets\AClassProject\Scripts\LookAtPlayer.js:9)
UnityEngine.Object:Internal_InstantiateSingle(Object, Vector3, Quaternion)
UnityEngine.Object:Internal_InstantiateSingle(Object, Vector3, Quaternion)
UnityEngine.Object:Instantiate(Object, Vector3, Quaternion)
Spawner:Update() (at Assets\AClassProject\Scripts\Spawner.js:17)

Well, then there’s no object called “Player”. Ideally you either check for null reference exceptions or you’re 100% sure they will never occur.

–Eric