C#: design time assigned object unable to find component

I have experienced a problem when converting some of the tutorial game “3D Platform Game” from JS to C#.

In the SmoothFollowCamera.js script there is this line:

controller = target.GetComponent(ThirdPersonController);

That I have translated into:

controller = target.GetComponent(typeof(ThirdPersonController)) as ThirdPersonController;

The target variable is assigned at design time and it works just fine using the Javascripts, but returns null in the C# scripts.

I was able to do a work-around using this:

controller = GameObject.Find(target.name).GetComponent(typeof(ThirdPersonController)) as ThirdPersonController;

Here is a cooked down script that can be tested:
CameraScript.cs attached to Main Camera

using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour {
	
	public Transform target;
	
	void Awake() {
		// doesn't work
		PlayerScript playerScript1 = target.GetComponent(typeof(PlayerScript)) as PlayerScript;
		print("script: "+playerScript1.name);
		
		// works
		PlayerScript playerScript2 = GameObject.Find(target.name).GetComponent(typeof(PlayerScript)) as PlayerScript;
		print("script: "+playerScript2.name);
	}
}

PlayerScript.cs attached to any object, remember to assign the object with this script to the variable target on the Main Camera

using UnityEngine;
using System.Collections;

public class PlayerScript : MonoBehaviour {
	// empty
}

Any ideas? Thanks in advance…

While it might not make much of a difference, using as-cast is faster but will return null if the cast failed. Try getting the component like this:

PlayerScript ps = (PlayerScript)target.GetComponent(typeof(PlayerScript));

Additionally, remember that GetComponent will only look for the component on the game object you specify, not it’s children, if you need the script and it’s on a child of target you will have to use GetComponentInChildren() instead.

There’s no reason one would work while the other doesn’t that I can think of short of them calling GetComponent on 2 different objects - I know GameObject.Find will return a gameObject, but target is a Transform - though that shouldn’t make a difference, you could try this:

PlayerScript playerScript1 = target.gameObject.GetComponent(typeof(PlayerScript)) as PlayerScript;

If that still fails it will verify the last remaining theory I have which is when you do GameObject.Find with the target’s name, you might be getting back a different object than what target is actually assigned to. Verify that the game object on target and the one returned from Find are actually the same game object. Hopefully this can get you pointed in the right direction.

try something like

private ThirdPersonController controller;
void Awake()
{
   controller = GetComponent<ThirdPersonController >();
}

Banzaï