- Home /
Confused as to why I'm getting a NullReference Exception
I have no clue as to why I'm getting a NullReference exception, since I did the same code in a different script and it works perfectly. Here's the full error: NullReferenceException: Object reference not set to an instance of an object TurretControl.Shoot (Int32 seconds) (at Assets/Custom/Scripts/TurretControl.cs:50) TurretControl.Update () (at Assets/Custom/Scripts/TurretControl.cs:34)
And here's the code of TurretControl.cs:
using UnityEngine;
using System.Collections;
public class TurretControl : MonoBehaviour
{
public Transform target;
public Transform bulletPrefab;
public float viewDistance;
public float damp;
public float bulletSpeed;
private int savedSeconds;
void Start()
{
}
void Update()
{
if(target)
{
float distance = Vector3.Distance(transform.position, target.position);
Quaternion rotate = Quaternion.LookRotation(target.position - transform.position);
if(distance <= viewDistance)
{
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
int seconds = (int)Time.time;
int odd = (seconds % 2);
if(odd == 0)
{
Shoot(seconds);
}
}
}
}
void Shoot(int seconds)
{
if(seconds != savedSeconds)
{
savedSeconds = seconds;
GameObject bullet = Instantiate(bulletPrefab,
GameObject.Find("turretFireBallSpawn").transform.position,
Quaternion.identity) as GameObject;
bullet.rigidbody.AddForce(transform.forward * (bulletSpeed * 1000));
}
}
}
And this is line 50: bullet.rigidbody.AddForce(transform.forward * (bulletSpeed * 1000));
Answer by Eric5h5 · Nov 09, 2012 at 07:26 PM
Your bulletPrefab is a Transform yet you are trying to instantiate a GameObject from it.
I changed it to GameObject and it works. I don't see why it doesn't work in this script, yet getting the player to fire has bulletPrefab as a Transform and it works without problems, which uses the same code for instantiation. Also, what threw me off, is when I changed Transform to GameObject, in the Inspector it said "Type $$anonymous$$ismatch" which made me think it was a problem, but I just had to re-select the prefab.
Thanks for the help :)