NullReference. Need Help.
I am using a variable from another script (facingRight). I get the error NullReferenceException, and I cant figure out what exactly I need to reference.
public class BulletTrail : MonoBehaviour {
public int moveSpeed = 0;
private PlayerController playerController;
void Awake()
{
playerController = transform.root.GetComponent<PlayerController>();
}
void Update()
{
if (!playerController.facingRight)
{
transform.Translate(Vector3.left * Time.deltaTime * moveSpeed);
Destroy(gameObject, 1);
}
if (playerController.facingRight)
{
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
Destroy(gameObject, 1);
}
}
}
Answer by Jessespike · Jul 20, 2016 at 07:31 PM
I'm guessing playerController is failing to get the component, which throws the error when you try to use it.
void Awake()
{
playerController = transform.root.GetComponent<PlayerController>();
}
^ This, are you sure this is working? Verify with a Debug.Log:
Debug.Log("is playerController null? " + (playerController == null));
Make adjustments so playerController is not null.
I put that in and it says its true and then spams me with the error.
yes, the playerController is null. It's not on the transform's root. Find a new way to store the reference. Either make playerController into a public and delete the Awake function OR update the Awake code so it points to the transform with the component. I don't know how you organized the objects, so I can't say what the code will look like. $$anonymous$$aybe:
playerController = transform.GetComponent<PlayerController>();
or maybe even:
playerController = FindObjectOfType<PlayerController>().transform;
I don't understand, and I tried it, it didn't work :P what do you mean not on the transform's root?
PlayerController component needs to be on a GameObject so it can be found
Your answer
Follow this Question
Related Questions
Javascript error 1 Answer
List suddenly auto-clear after WebRequest (in another Script)? 1 Answer
Unity3d Script does not work anymore 1 Answer
C# - Cannnot access variable in another script unless I get the component everytime. 1 Answer
Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers