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…