- Home /
NullReferenceException Object reference error
I am trying to get this script to create a fireball. This is based on the tornadotwins tutorials, however their tutorials are in javascript and I am trying to write my version of the program in C#. When I run this code, when the spacebar is pushed the fireball is created at the spawn point, but doesn't go anywhere. Also the camera view jumps out of whack and shows me something random on the scene and pauses the game and I have to unpause. So my question is really in two parts, how do I fix the null reference, and how do I get the fireball to actually move after being fired? Here is my script
using UnityEngine; using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class movementScript : MonoBehaviour {
public float speed = 25.0F;
public float rotateSpeed = 3.0F;
public Transform bulletPrefab;
void Update(){
CharacterController controller = GetComponent();
transform.Rotate (0,Input.GetAxis("Horizontal")*rotateSpeed,0);
Vector3 forward = transform.TransformDirection(Vector3.forward);
float curSpeed = speed*Input.GetAxis("Vertical");
controller.SimpleMove(forward*curSpeed);
if(Input.GetButtonDown("Jump")){
Rigidbody bullet;
bullet = Instantiate(bulletPrefab, GameObject.Find("spawnPoint").transform.position, Quaternion.identity) as Rigidbody;
bullet.velocity = transform.TransformDirection(Vector3.forward * 200);
}
}
}
Answer by Mikilo · May 07, 2013 at 01:28 PM
Hi!
I guess you should use a GameObject instead of transform for bulletPrefab. [Line 3] Also, when you Instantiate [Line 13], it returns a GameObject, you need to cast it GameObject. Afterward, you can retrieve the Rigidbody component and set the velocity by using AddForce.
Here is the example:
public float speed = 25.0F;
public float rotateSpeed = 3.0F;
public GameObject bulletPrefab;
void Update()
{
CharacterController controller = GetComponent();
transform.Rotate (0,Input.GetAxis("Horizontal")*rotateSpeed,0);
Vector3 forward = transform.TransformDirection(Vector3.forward);
float curSpeed = speed*Input.GetAxis("Vertical");
controller.SimpleMove(forward*curSpeed);
if(Input.GetButtonDown("Jump"))
{
GameObject bullet = Instantiate(bulletPrefab, GameObject.Find("spawnPoint").transform.position, Quaternion.identity) as GameObject;
bullet.rigidbody.AddForce(Vector3.forward * 200, ForceMode.VelocityChange);
}
}