I am having problems with my instantiate variable. This is from my “GameHandler” script, that is instantiating a turret pod on button down and turns off the gravity on its rigid body. Then on button up, I would like to turn on the gravity on the turret pod. Getting null reff error from the second newTurretPod variable under the GetButtonUp statement. Here is my code:
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
var newTurretPod = Instantiate(turretMisslePod, summonObjectPos.position, summonObjectPos.rotation);
newTurretPod.GetComponent(TurretPod).GravityOff();
}
if(Input.GetButtonUp("Fire1"))
{
newTurretPod.GetComponent(TurretPod).GravityOn();
}
}
If I am not able to do this, another method would be nice. Also I want it in my game handler script cause I wish to put all my button statements in that script and not get confused when I finish implementing the rest.
Thank You: james
Your problem is on line 5:
var newTurretPod = Instantiate(turretMisslePod, summonObjectPos.position, summonObjectPos.rotation);
You’ve declared ‘newTurretPos’ within the scope of Update(). This makes it a local variable to the function. It loses it value between calls to Update(), and you will not have a GetButtonDown() and GetButtonUp() in the same frame. You need to put the ‘newTurretPod’ variable at the top of the file:
private var newTurretPod : TurretPod;
And you need to remove the ‘var’ on line 5.
Well I am going to have to answer one of my own questions again…
The problem was setting a new variable up top like robertbu said but with :
private var newTurretPod : GameObject;
Not:
private var newTurretPod : TurretPod;
Then you have to remove the var from:
newTurretPod = Instantiate(turretMisslePod, summonObjectPos.position, summonObjectPos.rotation);
This is my script with these elements to make this work:
var turretMisslePod : GameObject;
var summonObjectPos : Transform;
private var newTurretPod : GameObject;
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
newTurretPod = Instantiate(turretMisslePod, summonObjectPos.position, summonObjectPos.rotation);
newTurretPod.GetComponent(TurretPod).GravityOff();
}
if(Input.GetButtonUp("Fire1"))
{
newTurretPod.GetComponent(TurretPod).GravityOn();
}
}
“TurretPod” is the name of the script that is attached to the object that is getting Instantiated.
“GravityOn() & GravityOff()” are the functions inside the TurretPod script that this script is calling.
Hope this helps someone
James