- Home /
Replace GameObject with another GameObject
Guys, I got a problem with the replacement of an Object.
Well. My character "Obj_Char" should be change in to another Object, Object "Obj_Explosion"
If "Obj_Char" is onTrigger with a rock, then "Obje_Char should change in to "Obj_Explosion". Someone can help me out with this?
I got this for my Rock JavaScript;
var CharExplode : GameObject;
var Explosion : GameObject;
function OnTriggerEnter(other : Collider)
{
if (other.gameObject.CompareTag("CharTag")) {
CharExplode = Explosion;
}
}
But this doesn't work. So please help :D
Thanks in advance
Answer by robertbu · Jun 11, 2013 at 10:47 PM
I'm not sure what replacement means to you, nor have you described any parent/child relationship between these two game objects. Assuming the explosion game object is deactivated you might be what something like this:
#pragma strict
var charExplode : GameObject;
var explosion : GameObject;
function OnTriggerEnter(other : Collider) {
if (other.gameObject.CompareTag("CharTag")) {
charExplode.SetActive(false);
explosion.transform.position = charExplode.transform.position;
explosion.transform.rotation = charExplode.transform.rotation;
explosion.SetActive(true);
}
}
It says,
'position' is not a member of 'UnityEngine.GameObject'.
and
'rotation' is not a member of 'UnityEngine.GameObject'.
Fixed. Usually I use Transform ins$$anonymous$$d of GameObject for my linked variables.
I got this right now, but nothing happens
var CharExplode : Transform;
var Explosion : Transform;
function OnTriggerEnter(other : Collider){
if (other.gameObject.CompareTag("CharTag")) {
Explosion.position = CharExplode.position;
Explosion.rotation = CharExplode.rotation;
}
}
Note the code I posted doesn't "replace" anything. It puts one game object at the position of another, and disables the original.
Put a Debug.Log() statement to verify the code is being executed.
Look at the position in the Hierarchy to see if both game objects exist and are at the some position.
$$anonymous$$ake sure that 'explosion' is enables and visible.
SetActive is a member of a GameObject. since you rewrote your code to use Transforms, you can do:
Explosion.gameObject.SetActive(true);
Note that variable names "should" be in lower case. The compiler does not care, but most experienced folks on this list use this convention, so using upper case makes your code harder to understand.
Answer by MRCty · Aug 05, 2014 at 09:47 AM
I also have the same need. I would replace GameObject1 with GameObject2, not just repositioning GameObject2 and deactivate GameObject1.
Assume that I have a GameObject parent and GameObject1 is a child of the parent. Then I want to switch GameObject1 with GameObject2, by code.
Is it possible?