I've searched a lot for this question but there was no answer that could solve the problem I'm having. I'm new to unity and a very naive developer.

I'm making a game in unity using c# and it's like a bird that throws eggs in down projectile and when the egg hit the container it should destroy egg and the container sprite should change to a sprite which shows that the egg is inside the container.

It would be really helpful if someone could answer with a example code and I can implement this. Rest of the game is working fine projectile and hit. There are check points on egg.cs in OnTriggerEnter2D that if target.gameObject.tag == "Container" now here I need to change the container to another sprite I've and this should move in the direction of container.

Here is the code which changes the sprite, but it changes the egg sprite not the container sprite.
First the declaration:

public Sprite changedContainer; //here I've set the sprite of Changed Container
private SpriteRenderer spriteRend;

Then in the start method:

spriteRend = GetComponent<SpriteRenderer>();

and finally my onCollision Trigger method: (Read the comment in my code)

void OnTriggerEnter2D(Collider2D target)
        if (target.gameObject.tag == "Container") //if the egg collide with container
            transform.GetComponent<SpriteRenderer> ().sprite = changedContainer; <br //which it did successfully
            Instantiate(changedContainer, target.gameObject.transform.position, Quaternion.identity); //as it is mentioned that target.gameobject.transform.position but it still takes the egg projectile

So how to change the spite of container? I think I'm in the wrong class I should be doing this in the container class. But it is the projectile of egg that collides not the container that collides with egg.


1 Answer 1


if egg.cs is attached to the egg, then writing:

transform.GetComponent<SpriteRenderer> ().sprite = changedContainer;

will change the egg component, so maybe use

target.gameObject.transform.GetComponent<SpriteRenderer> ().sprite = changedContainer;
  • \$\begingroup\$ This transform.GetComponent<SpriteRenderer> ().sprite = changedContainer; worked just perfectly fine for me and it changed the container not the egg. I used it inside OnTriggerEnter2D where the container is respawning. \$\endgroup\$ Mar 24, 2015 at 5:30
  • \$\begingroup\$ Sry maybe try to let me see more code, so at the end you have 2 changedContainer? you want the egg to be destroyed? I don't understand also why you use 'Istantiate()' if you want only to change the sprite. \$\endgroup\$
    – skind
    Mar 24, 2015 at 21:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .