//Moving around
var speed = 3.0;
var rotatespeed = 8.0;
//Shooting
var bullitPrefab:Transform;
function Update ()
{
var controller : CharacterController = GetComponent(CharacterController);
// rotate around y - axis
transform.Rotate(0, Input.GetAxis ("Horizontal") * rotatespeed, 0);
// Move forward / backward
var forward = transform.TransformDirection(Vector3.forward); //Vector3.forward
var curSpeed = speed * Input.GetAxis ("Vertical");
controller.SimpleMove(forward * curSpeed);
//shooting!
if(Input.GetButtonDown("Fire1"))
{
var bullit = Instantiate(bullitPrefab,
GameObject.Find("shootingPoint").transform.position,
Quaternion.identity);
bullit.rigidbody.AddForce(transform.forward * 2000);
}
}
A null reference exception is when you create a var and you say that it is pointing to an object, but in reality you did not say what object it is pointing to. There is no object to work with and thus the program is not happy.
Your problem is these two lines
var controller : CharacterController = GetComponent(CharacterController);
//...
controller.SimpleMove(forward * curSpeed);
the method GetComponent will return a null
reference if there is no component found of the inputted type, or if there is an error with how you cast it into your var.
Then, you try to use the var returned by this method without checking if(controller != null)
You can try to fix it by making sure that there is a CharacterController attached to your GameObject. Next, if that does not work, perform the check if(controller != null) before working with the Object.
Try putting this line of code at the top of your file
#pragma strict
If your error is caused by a casting problem, adding that line will make it so that the program will not compile until the problem is fixed, and generally give you more information about the problem.
You can also try to use one of these lines instead of your current implementation:
var controller : CharacterController = GetComponent(CharacterController) as CharacterController;
var controller : CharacterController = GetComponent.<CharacterController>();
On an unrelated note, Do not use the GetComponent Method inside of Update or LateUpdate if you can avoid it. It is a very slow function and it will lower your frame rate if you call it in update. Try calling it only once in Start and it will be more reliable and efficient.
Hope this helped <("<)(^"^)(>")>
In line 6 :
var bullitPrefab : Transform;
Transform is not use in there, because in line 24
bullit.rigidbody.AddForce(transform.forward * 2000);
You may have a rigidbody in the bullitPrefab.
so you should change line 6 →
var bullitPrefab : Rigidbody;
And the bullitPrefab have rigidbody too.