It is rather strange that you are trying to add force to a prefab. Could be that it doesn’t have rigidbody on it because it’s not instantiated.
You can narrow the problem more by putting null checks or by splitting the expression into several parts (not just putting some whitespace as debugger will just ignore them)
If your variable laserBeam is your prefab, then that would explain why this isn’t working. You need to add force to an instance of the prefab, not the prefab itself.
Looking at that tutorial, the closest thing I can spot to your code is a case of instantiating a “Bullit”, where he has a variable called BullitPrefab, then uses Instantiate and assigns the result to a variable called Bullit, then adds force to the rigid body of the newly created instance.
Are you doing the same thing? Also, in future, it’ll be helpful if you post more of your code, it’s difficult to tell where you’ve gone wrong from a single line.
That helps shine some light on this for me. So, I have my script attached to my gameObject “Gun01,” and my “laserBeam” prefab instance has a Rigidbody attached to it. But now insteand of shooting forward, the shot goes straight down the -Y axis (gravity is off). I’m still getting the same error. Here is the entire script that I’m using. The script is suppose to me a component of the “Gun01” right?
The best way to post code is to wrap it in code tags, like this : [CODE]code goes here[/CODE]
So other people can follow along, here is your code :
var laserBeamPrefab : Transform;
function Update ()
{
if(Input.GetButtonDown("Jump"))
var laserBeam = Instantiate(laserBeamPrefab, GameObject.Find("spawnPoint").transform.position,Quaternion.identity);
laserBeam.rigidbody.AddForce(transform.forward * 200);
}
Your null reference is being caused by your if statement. When you don’t include { }'s, the if statement evaluates the next line when the condition is true. So whenever the jump button is pushed, it is instantiating a laserbeam. However, the line after that, where you add force, is run every frame regardless of if the button was pushed (it’s outside the if statement). Since you’re adding force to an object that was never created, it’s a null reference.
You’ll want to define a block of code using { }, like this