- Home /
Question by
Yacob3 · Jul 07, 2013 at 11:20 AM ·
javascriptrigidbodyinstantiate
Can't instantiate a rigidbody
Here is my code:
var PlayerSpeed : int;
var PlayerLives : int;
static var PlayerScore : int;
var Projectile : Rigidbody;
function Update()
{
//Move Player
amtToMove = (PlayerSpeed*Input.GetAxis("Horizontal")) * Time.deltaTime;
transform.Translate(Vector3.right*amtToMove);
amtToMove = (PlayerSpeed*Input.GetAxis("Vertical")) * Time.deltaTime;
transform.Translate(Vector3.up*amtToMove);
if(Input.GetKeyDown("space"))
{
var tempProjectile : Rigidbody;
tempProjectile = Instantiate(Projectile,transform.positision,transform.rotation);
}
}
function OnGUI()
{
GUI.Label(Rect(10,10,200,50),"Score: " + PlayerScore);
GUI.Label(Rect(10,30,200,50),"Lives: " + PlayerLives);
}
When I test it, I keep getting the an error message in the console tab:
NullReferenceException: Object reference not set to an instance of an object PlayerScript.Update () (at Assets/Scripts/PlayerScript.js:25)
I'm not sure what I'm doing wrong and was wondering if someone could help me solve this issue.
Comment
Answer by arcan3artist · Jul 07, 2013 at 12:23 PM
You should be instantiating from a game object prefab and getting the rigid body component from that game object.
// SLOT OF GAME OBJECT PROJECTILE PREFAB
var projectile : GameObject;
// THIS CODE GOES INSIDE KEYDOWN
var projObj : GameObject;
projObj = Instantiate(projectile, transform.position, transform.rotation);
var projRig : Rigidbody = projObj.rigidbody;
I'm still getting the same issue.
I don't know what I'm doing wrong.
Have you attached a GameObject with a rigidbody to the Projectile slot in the inspector window?
Also typo on 25, should be transform.position not transform.positision.