Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Swap Sprite with another sprite with bones/skinning/weight

Discussion in 'Scripting' started by Albion-Wizard, May 16, 2024.

  1. Albion-Wizard

    Albion-Wizard

    Joined:
    Sep 19, 2013
    Posts:
    1
    Hello everyone

    Im building a project were a user shall scan his/her drawing of a character with a webcamera and apply that drawing as a spawnable sprite with bones and animation in a 2d world. Im currently have created a prefab with a blank figure were I made bones, skinning and some basic animation, were I'm gonna use that prefab to populate the world. This prefab is gonna use the scanned drawing as a sprite.

    Changing the prefab to have the scanned texture is a success, but the animation and weighting are lost. Now I want to try if I can get the prefabs bones and weight and apply to the scanned sprite. I searched the web for how to do this, and came up with this code:

    Code (CSharp):
    1.  [SerializeField] private GameObject targetSpriteSkin;
    2.     private Sprite spriteSkin;
    3.     // Start is called before the first frame update
    4.     void Start()
    5.     {
    6.         spriteSkin = targetSpriteSkin.GetComponent<SpriteRenderer>().sprite;
    7.         SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
    8.         SpriteBone[] bones = spriteSkin.GetBones();
    9.         NativeArray<Matrix4x4> bindPoses = spriteSkin.GetBindPoses();
    10.  
    11.         spriteRenderer.sprite = spriteSkin;
    12.  
    13.         spriteRenderer.sprite.SetBones(bones);
    14.         spriteRenderer.sprite.SetBindPoses(bindPoses);
    15.         spriteRenderer.sprite.SetVertexAttribute<Vector3>(UnityEngine.Rendering.VertexAttribute.Position, positions); // how do I retrieve this?
    16.         spriteRenderer.sprite.SetVertexAttribute<BoneWeight>(UnityEngine.Rendering.VertexAttribute.BlendWeight, weights); // how do I retrieve this?
    17.         spriteRenderer.sprite.SetVertexAttribute<Color32>(UnityEngine.Rendering.VertexAttribute.Color, colors); // how do I retrieve this?
    18.  
    19.     }
    But I'm unsure how I can get positions, weights and color data for setting the last lines for SetVertexAttribute.

    Other solution I tried was to use SpriteLibrary to swap sprites, but is hard to at runtime with a scanned texture from a webcamera.

    My current solution is I have a 3D mesh that acts as a 2D plannar character. When user scannes his/her drawing, the drawing will apply as a texture for the 3D figure. But it would be good if I use a 2D character since its a 2d project.

    Much help is appreciated.
     
    jmancoder likes this.