- Home /
Object reference error in my rocket script
Hi, I am getting an error in my script here:
var linePrefab : GameObject;
var hitPrefab : GameObject;
var range = 0.00;
var damage = 0.00;
var layerMask = 1 << 8;
var reloadTime = 0.5;
var ammoCount = 20;
private var lastShot = -10.0;
var hit : RaycastHit;
function Start() {
}
function Update() {
if(Time.time > reloadTime + lastShot && ammoCount > 0)
Fire();
}
function Fire() {
newLineObject = Instantiate(linePrefab);
newLine = newLineObject.GetComponent(LineRenderer);
if (Physics.Raycast (transform.position, Vector3.forward, Mathf.Infinity, layerMask))
{
newLine.SetPosition(0, transform.position);
newLine.SetPosition(1, hit.point);
if(hitPrefab) Instantiate(hitPrefab, hit.point, Quaternion.LookRotation(hit.normal));
hit.collider.gameObject.GetComponent("PlayersHealth").curHealth -= 10;
hit.collider.gameObject.SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
Debug.Log("IVE BEEN HIT!!!!");
}
else
{
newLine.SetPosition(0, transform.position);
newLine.SetPosition(1, transform.TransformPoint(Vector3.forward * range));
}
}
The error occurs at the line: hit.collider.gameObject.GetComponent("PlayersHealth").curHealth -= 10;
The error is saying "Object reference not set to an instance of an object." Can someone take a look at this and give me an idea to what I'm doing wrong? Thank you.
Answer by ObviouslyInsane · Sep 22, 2011 at 01:12 AM
Ok, first of all thank you harmless for helping me out. You solved half my problem, but now I have another one. Now the enemies are only able to cast the ray in the direction they are facing when the game starts. Here is my updated physics statement:
if (Physics.Raycast(transform.position, Vector3.forward, hit))
I'm sure this is where the problem is because its the only line I changed. Could you possibly give me a little more insight? Thank you.
What, you want the enemies to be firing contiuously? Then you just have to call Fire() every frame from your Update loop.
Ok, forget what I said about that, they ARE shooting more than one ray. But, I still have one problem, the rays are only being shot in one direction, it seems to be the direction the enemy is facing when the game starts.
ah, you should be using transform.forward, not Vector3.forward. Vector3.forward will always = (1, 0, 0)- it is a hardcoded shortcut!
Answer by loopyllama · Sep 21, 2011 at 05:46 AM
you never do assign hit to anything, so hit.collider.gameObject is null. pass it into your physics statement. For argument structure look here: http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html
choose one that takes an out hitinfo: raycasthit as an argument and pass in your hit variable.