Search Unity

SpriteRenderer changing texture UV offset

Discussion in 'Scripting' started by PenDigi, Nov 8, 2015.

  1. PenDigi

    PenDigi

    Joined:
    Sep 19, 2015
    Posts:
    14
    Hello all,

    I am trying to get my 2D background sprite to scroll infinitely against the player's movement. Similar to what you would see in a 2D top down space explorer game.

    Currently I have this code which I saw from numerous tutorials

    SpriteRenderer sr = GetComponent<SpriteRenderer> ();
    Material mat = sr.material;
    Vector2 offset = mat.mainTextureOffset;
    offset.x += Time.deltaTime;
    mat.mainTextureOffset = offset;
    print (mat.mainTextureOffset);

    This code is in the Background Controller script attached to my Background Game object. For now I just want to change its UV texture offset values so that it moves. But no matter the value of the offset the background does not move!

    Im not sure if im actually doing the right thing but it seems that all the tutorials I've seen where the object is stationary but its texture moves is done in this manner.

    Please help. Thanks

    Update: Okay looking back at the component inspector for unity, I noticed a warning stating that mainTextureOffset/scale was set and that this variable is incompatible with sprite renderer.
    That is probably why this UV trick is not working. Does any1 know a workaround for this?
     
    Last edited: Nov 8, 2015
  2. PenDigi

    PenDigi

    Joined:
    Sep 19, 2015
    Posts:
    14
    Alright guys so I've solved it.

    UV offset is a 3D feature and hence SpriteRenderer does not use UV coordinates.

    A simple fix is to create a 3D Plane object and a Unlit/Texture Material with the image file you wish to use. Attach the material to your plane object and the code should work (using MeshRenderer instead of SpriteRenderer)
     
    tko1975 likes this.