Search Unity

How to scale and offset UV at editor time through script

Discussion in 'World Building' started by FeastSC2, Dec 6, 2019.

  1. FeastSC2

    FeastSC2

    Joined:
    Sep 30, 2016
    Posts:
    978
    Hello,

    I want to use ProBuilder to scale and offset its UV's so that I don't have to create different materials for every object. This is something ProBuilder can do through its UV editor interface but I want to do it with a component that I attach to the gameObject, so it's quick and easy to modify.

    How can I scale and offset UV's through script?
    Thanks for any help.
     
  2. SgtLame

    SgtLame

    Joined:
    Nov 26, 2015
    Posts:
    129
    Hi,

    I work on very simple meshes, so I'm far from being good at this, but first of all, I think you need to study how UVs are stored in ProBuilder.
    I think you should start with building a simple quad, opening the UV editor and running this editor code:

    Code (CSharp):
    1. List<Vector4> uvs = new List<Vector4>();
    2.  
    3. pbMesh.GetUVs(0, uvs); // pbMesh is your ProBuilderMesh object.
    4.  
    5. foreach (Vector4 uv in uvs)
    6. {
    7.      Debug.Log(uv);
    8. }
    so you can see how it's made.

    Then, I don't know if this is the proper or best way to do it, but so far it's been working fine for me:

    Code (CSharp):
    1. List<Vector4> UV = new List<Vector4>(); // new UVs
    2.  
    3. // First, set UVs to manual. pbMesh is your ProBuilderMesh object.
    4. foreach(Face f in pbMesh.faces)
    5. {
    6.     f.manualUV = true;
    7. }
    8.  
    9. //Then, build your UVs structure
    10. UV.Add(new Vector4(someX, someY)); // z and w coordinates are unused.
    11. // (...) and so on
    12.  
    13. // Apply UVs
    14. pbMesh.SetUVs(0, UV);
    15. pbMesh.Refresh();
    16.  
    Hope that helps.
     
    FeastSC2 likes this.