1
votes

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.

2
"Should I not destroy the white balls and instead somehow turn them into green balls? Is that possible?" yes you should do that. either go the enable/disable approach of object pooling (youll need that if you plan replace the balls with actual models in the future) unity3d.com/de/learn/tutorials/topics/scripting/object-pooling or switch out their shared material docs.unity3d.com/ScriptReference/Renderer-sharedMaterials.htmlyes

2 Answers

3
votes

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!

2
votes

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.