- Home /
how to re-assign transform/rigidbody at runtime ?
at start playerA spawns in the scene
camera finds playerA by FindGameObjectWithTag, at start (both playerA and playerB are tagged "Player")
public Transform playTrans;
public Rigidbody rb;
void Start ()
{
findStuff();
}
public void findStuff()
{
playTrans = GameObject.FindGameObjectWithTag("Player").transform;
rb = GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody>();
}
camera starts following playerA
now, when playerA dies, it is destroyed, out of the scene,
playerB spawns in the scene.
camera is now suppose to follow playerB
but, playTrans and rb camera found at start, stays assigned to playerA's transform and rigidbody
so I re-run the function findStuff(); because now only gameobject with "Player" tag in scene is playerB
so it should find playerB's transform and rigidbody right?
but nope. playTrans and rb stays assigned to playerA's transform and rigidbody.
camera doesnt follow playerB and gives error that rb is destroyed.
how do I re-assign transform and rigidbody at runtime
If this is indeed true:
when playerA dies, it is destroyed
... then both playTrans = null
and rb = null
Therefore, when you call findStuff()
again it should have no problem setting the variables to PlayerB, and:
playTrans and rb stays assigned to playerA's transform and rigidbody
cannot be possible because playerA is null... if it's properly destroyed...
You should post more relevant code. something you're saying is not right.
i used
Destroy(GameObject.FindGameObjectWithTag("Player"));
to destroy existing player before instantiating another player.
is this not right ?
It would destroy it, if it was already existing in the scene, and active. However, if not spawned yet, or inactive, the FindGameObjectWithTag
would not find it, so would not destroy it (just yet).
Your answer
Follow this Question
Related Questions
object rotation with rigidbody component 1 Answer
problem with rigidbody.position 1 Answer
2d Circle won't change size 0 Answers
Intercepting Alghorithm not wok properly 1 Answer
Object not moving,Object not moving in any direction 1 Answer