Don't understand why this on collision script doesn't work.

I don’t know why this script doesn’t work. Am I just misunderstanding something simple. This is the error I get: NullReferenceException: Object reference not set to an instance of an object. This is my script:

using UnityEngine;
using System.Collections;

public class ForceCalculator : MonoBehaviour {

public float angle = 0;

public GameObject Player;

// Use this for initialization
void Start () {
	Player = GameObject.Find ("player");
		}

// Update is called once per frame
void Update () {
}

public void OnCollisionEnter(Collision col){
	if(col.gameObject.name == "Weapon"){
		Player.GetComponent<PowerBar>().Force = (Player.GetComponent<PowerBar>().OriginalRotation - transform.Find("player").eulerAngles.y) * Player.GetComponent<PowerBar>().thePower;
		Player.rigidbody.AddForce(-transform.Find("player").forward * Player.GetComponent<PowerBar>().Force);

}
}
}

Please don’t link me to script reference. I’ve read it and it hasn’t helped. Please help. I have updated the script with improvements you’ve given me so far. But I still get the same error.

So, I’m not positive on what you’re attempting to do, but there are a few options.

If your “PowerBar” is a data storage object, then you need a reference to it from the inspector (There are other ways, but that is the easiest). So after you have the reference to the instance, then you can quickly grab the variables associated to it.

You get the reference from the inspector by having…

public PowerBar PowerBarInstance;

Then just reference PowerBarInstance.

Alternatively, if the PowerBar variables are on the game object that you just collided with, then you can simply put in…

col.gameobject

in order to reference the gameObject that you just collided with, and you can go from there in order to get the information needed.

And in case you’re wondering about how to get a component from the game object then look up the GetComponent method in the GameObject class for help with that. Hope this helps.

Apparently the problem was in the way I worded the transform. It should have been written:’ -Player.transform.forward’ and not ‘-transform.Find(“player”).forward’