- Home /
Turning a gameobject's gravity on/off
So here's my code:
#pragma strict
var coconutPrefab : GameObject;
var cocoHolder : GameObject;
var player : Transform;
private var drawGUI = false;
private var cocoClone : GameObject;
function Start () {
var cocoClone:GameObject = Instantiate(coconutPrefab, cocoHolder.transform.position, cocoHolder.transform.rotation);
cocoClone.rigidbody.useGravity = false;
cocoClone.rigidbody.isKinematic = true;
cocoClone.transform.parent = cocoHolder.transform;
player = null;
}
function Update () {
if(drawGUI == true)
{
if(Input.GetKeyDown(KeyCode.E))
{
var tree = cocoHolder.transform.parent;
tree.animation.Play("TreeShake");
cocoClone.rigidbody.useGravity = true;
cocoClone.rigidbody.isKinematic = false;
drawGUI = false;
}
}
}
function OnTriggerEnter (theCollider : Collider)
{
if (theCollider.tag == "Player")
{
player = GameObject.FindGameObjectWithTag("Player").transform;
Debug.Log("Player has been found");
drawGUI = true;
}
}
function OnTriggerExit (theCollider : Collider)
{
if (theCollider.tag == "Player")
{
drawGUI = false;
transform.collider.isTrigger = false;
}
}
function OnGUI ()
{
if (drawGUI == true)
{
GUI.Box (Rect (Screen.width*0.5-100, 200, 200, 22), "Press E To Shake Tree");
}
}
When I press E in the Update, these two lines throw me a Null reference error:
cocoClone.rigidbody.useGravity = true;
cocoClone.rigidbody.isKinematic = false;
I also tried changing the gameobject name from those two lines to coconutPrefab, because I had read that when you instantiate a prefab, the variable for the prefab refers to the clone. It doesn't give me an error, but it also doesn't add gravity to the coconut when I press E either. So I'm stumped, what am I doing wrong?
Answer by karlhulme · Jan 29, 2014 at 11:28 PM
I think you're getting a NullReferenceException because cocoClone is null. This is because the start function is creating a new local variable, rather than assigning a value to the member variable. So basically change this...
var cocoClone:GameObject = Instantiate(coconutPrefab, cocoHolder.transform.position, cocoHolder.transform.rotation);
to this...
cocoClone = Instantiate(coconutPrefab, cocoHolder.transform.position, cocoHolder.transform.rotation);
That worked, thanks! But now I'm having a different problem. Whenever I press 'E', the parent object and all children move about 16 units on the Z axis. I tried reattaching the prefabs/objects to the script in the inspector, and that didn't do it. I'm pretty stumped:|.
I'm looking but I can't see what would cause that from the code.
I think your best bet is to mark this question as answered, and then a post a new separate question explaining both the behaviour you expect and the behaviour you're actually seeing. And include a screenshot of both the scene and the game object hierarchy.