- Home /
Replace variable with new game object after it is made null - not working
Hi - I've written a script so that a gameobject follows the first and third person controller, depending on which one is active. (This bit works). Halfway through the game- the third person controller is destroyed and a new third person controller is created.
I then want the gameobject to follow the new third person controller, once the original third person controller is destroyed - but I can't work out how to correctly phrase it in the script.
This is what I've got - it's not throwing errors, but the gameobject isn't following the new third person controller as it should:
var targetF : Transform;
var targetT : Transform;
var firstPerson : GameObject;
function Update () {
if (firstPerson.GetComponent(CharacterController).active) {
transform.position = Vector3.MoveTowards(transform.position,targetF.transform.position, 0.03f);
transform.LookAt(targetF);
}
if (!firstPerson.GetComponent(CharacterController).active) {
transform.position = Vector3.MoveTowards(transform.position,targetT.transform.position, 0.08f);
transform.LookAt(targetT);
}
if (targetT == null) {
var targetT = GameObject.FindGameObjectWithTag("Carl");
}
}
Any ideas on how to phrase it better?
Thanks, Laurien
If I were you, I would avoid GetComponent and FindGameObject inside an Update loop. Then, have a GameObject that is the follow target ( GameObject followTarget
) and always follow it. Finally, set this object to point to the correct controller (i.e. when you destroy one, make it equal the other).
Thanks! But how do I make the game object equal to the other? (Sorry - new to coding)
Would something like this work for you? (pseudocode):
var controller1 : GameObject;
var controller2 : GameObject;
var followTarget : GameObject;
function Start() {
followTarget = controller1;
}
function Update() {
$$anonymous$$oveTowards( followTarget );
if( Condition To Destroy controller1 ) {
Destroy( controller1 );
followTarget = controller2;
}
}
Your error I am guessing is at followTarget = targetT;
. Convert private var followTarget: GameObject;
to private var followTarget: Transform;
and it should work. The error tells you you are using GameObject where you should be using Transform.
As for the Condition to Destroy - I was only using this text to say: this is where you should write any condition that causes the destruction of one controller, and switch to the other.
Yeah, that's probably one way to handle this. You should probably search for information about referencing other objects and components, there are many different ways of doing it, each more suitable for different situations.