Unity3D – Texture Mover – Javascript

How to move texture via code.

Create a Plane with
– Material with a _MainTex (if you use a diffuse material it is the main color texture)
– TextureMover.js

Simple code:


#pragma strict

    // Scroll main texture based on time
	var scrollSpeed : float; // Assign in Inspector, start try 0.5

function Start () {
    // setup Main Texture (scaleX,scaleY) 
    // x = 0.5 perchè la texture che uso è il doppio in larghezza della dimensione del piano
    // il piano è 16:9, ta texture 32:9 per avere un landscape più ampio
	renderer.material.SetTextureScale ("_MainTex", Vector2(0.5,1));
}// END Start()

function Update () {
        var offset : float = Time.time * scrollSpeed;
		renderer.material.SetTextureOffset ("_MainTex", Vector2(offset,0));
}// END Update()

Play to see the final result

Pro code:


#pragma strict

    var isVertical : boolean = false; // check in Inspector if you need a vertical scrool 
    
    var invertDirection : boolean = false; // check in Inspector if you need change scrool direction
    
    // Scroll main texture based on time
	var scrollSpeed : float; // Assign in Inspector, start try 0.5
	
	var scaleX : float; // X scale of the texture
	var scaleY : float; // X scale of the texture

function Start () {

    // setup Main Texture (scaleX,scaleY) START ###############################################
    // ad esempio scaleX = 0.5 se la texture che uso è il doppio in larghezza della dimensione del piano
    // il piano è 16:9, la texture 32:9 
	renderer.material.SetTextureScale ("_MainTex", Vector2(scaleX,scaleY));
	// setup Main Texture (scaleX,scaleY) END #################################################
	
}// END Start()

function Update () {

        MoveTexture(); // devo richiamarla da update perchè si deve aggiornare ad ogni frame
        
}// END Update()

function MoveTexture(){

        var offset : float; // lo spostamento della texture...
        
        // left->right or right->left or up->down or down->up ----------------------------------------------
	    if (invertDirection){ // positivo
	    offset = Time.time * -scrollSpeed; 
	    } 
	    
	     if (!invertDirection){ // negativo
	    offset = Time.time * scrollSpeed; 
	    }
        // vertical or horizontal  -------------------------------------------------------------------------
	    if (isVertical) { // in verticale 
	        renderer.material.mainTextureOffset = Vector2 (0, offset);  
	    }else{  // in orizzontale
	        renderer.material.mainTextureOffset = Vector2 (offset, 0);  
	    } 
  
}// END MoveTexture()


Setup in Inspector the value of variables

Play, you can change values on the fly into Inspector!