Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Changing a Sprite Midgame

Discussion in 'Getting Started' started by unity_3ddragon, May 13, 2024.

  1. unity_3ddragon

    unity_3ddragon

    Joined:
    May 13, 2024
    Posts:
    3
    I'm working on creating a game where the sprite gets a sword if they are above a certain height. I've only got two different sprites I need to switch between and really don't want to have to make an animation sheet. The code works to switch the sprite but when it switches anything new doesn't have a collider. Is there a way to add one. If more info is needed I can provide it. The switching code is below.
    Code (CSharp):
    1. if (transform.position.y >= 1)
    2.       {
    3.         this.gameObject.GetComponent<SpriteRenderer>().sprite = left;
    4.       }
     
  2. influjensbahr

    influjensbahr

    Joined:
    Aug 31, 2015
    Posts:
    47
    Hi! What kind of collider component do you have on the
    GameObject
    in question? Could you post a screenshot of all the components the
    GameObject
    has and also a bit more code surrounding the lines you've posted?
     
  3. unity_3ddragon

    unity_3ddragon

    Joined:
    May 13, 2024
    Posts:
    3
    This video shows everything (No audio unless I forgot to remove it) Both walls have polygon Colliders and there is nothing else to the code to change sprites other than what I've already shared
     
    Last edited: May 14, 2024
  4. influjensbahr

    influjensbahr

    Joined:
    Aug 31, 2015
    Posts:
    47
    I see, thank you for posting your video. When you add a
    PolygonCollider
    to the
    GameObject
    that has a
    SpriteRenderer
    attached, Unity automatically sets the
    PolygonCollider
    up to (approximately) match the borders of your
    Sprite
    .

    So, when you first create the object, the shape of the collider is set to the outline of your player character.

    What you need to do is update the shape of the
    PolygonCollider
    to match the newly displayed character that also has a sword. This thread here suggests a few ways of doing it and seems to be about a very similar situation:
    https://discussions.unity.com/t/refreshing-the-polygon-collider-2d-upon-sprite-change/107265/6