Hello all, thanks for all your help so far and in advance on this one and I’m almost done with this script (I think) and just having one more issue and I am not sure why…
Getting the error:
NullReferenceException: Object reference not set to an instance of an object
turretai2-1.fire () (at Assets/Scripts/turretai2-1.js:33)
Which is the vector3 line to shoot at the target. I have the object sourced, it stays sourced while playing. I have no idea why I’m still getting error and just really need a hand finishing this up… Thanks again all,
Gaspar
private var ammoprefab: Transform;
private var nextTime : float;
//start shooting
function Start () {
InvokeRepeating ("fire", 0, 0.3);
}
// Finding the closest target
function find() : GameObject {
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Enemy");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
for (var go : GameObject in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
//used to look at the target
function Update(){
var target = find();
transform.LookAt(target.transform);
}
//used to determine target and distance to shoot at
function fire(){
var target = find();
var range = 500;
if(Vector3.Distance(transform.gameObject.position, target.gameObject.position) < range)
shoot();
}
//used to fire the bullet
function shoot(){
ammoprefab = transform.FindObject("newbullet");
var ammo =
Instantiate(ammoprefab,transform.Find("f2").transform.position, transform.rotation);
ammo.rigidbody.AddForce(transform.forward *10000);
Destroy(ammo.gameObject, 1.5);
}