tryingtotryhard
tryingtotryhard

Reputation: 134

Destroy an object and replace with a prefab at original objects location?

enter image description here

The green balls search out for white ones and "infect" them. The white balls are destroyed but they come back at the point of origin. I've tried to make a variable of the position of the white balls but I keep running into "Can't convert Transform to Vector3" errors.

public Rigidbody prefabInfection;
public Transform infectLocation;

void OnCollisionEnter(Collision colInfo)
{
    if (colInfo.collider.tag == "Infection")
    {
        Destroy(gameObject);
        Instantiate(prefabInfection);
    }
}

That's the code that's currently being used on collision.

I'm new to Unity also. Should I not destroy the white balls and instead somehow turn them into green balls? Is that possible?

Instantiation seemed like the only way. All I want to do is replace the white "human" balls to green "infection" ones.

Upvotes: 2

Views: 1763

Answers (2)

Daxtron2
Daxtron2

Reputation: 1309

Because you're destroying the current object, your script will never instantiate the new object because it's been destroyed before it got the chance to.

Instantiate(prefabInfection, gameObject.transform.position);
Destroy(gameObject);

If you do it in this order, and pass in the position of the object, it should work how you intend it to.

EDIT: I've just learned that Destroy will actually wait until the current Update() frame has finished to destroy objects. I'm going to leave my answer up because I still think that's it is a better practice to call Destroy() last.

Upvotes: 2

Dan Puzey
Dan Puzey

Reputation: 34218

The error you're seeing is probably because you're using the Transform object instead of its .position. Assuming your code is a component on the white ball gameObject, try this:

public Rigidbody prefabInfection;

void OnCollisionEnter(Collision colInfo)
{
    if (colInfo.collider.tag == "Infection")
    {
        Destroy(gameObject);
        Instantiate(prefabInfection, transform.position, transform.rotation);
    }
}

By passing your transform.position to the Instantiate function, the new object will be created in the same position as the one you're destroying. Hopefully this is the behaviour you intended!

Upvotes: 3

Related Questions