Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Using UI button to change movie textures on object

Discussion in 'Scripting' started by s096268, Nov 4, 2015.

  1. s096268

    s096268

    Joined:
    Oct 28, 2015
    Posts:
    11
    Hi there,

    I'm just new to Unity and for a project I'm trying to change movie textures on an object (cube) with an UI button.
    I'm able to change the textures with the space bar (see example script below) but I can't figure out how to use an UI button instead of the space bar.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.UI;
    5. using UnityEngine.EventSystems;
    6.  
    7. public class CreateTexture : MonoBehaviour {
    8.     public Texture[] textures;
    9.     public int currentTexture;
    10.  
    11.     void Start()
    12.     {
    13.  
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update() {
    18.  
    19.         if (Input.GetKeyDown(KeyCode.Space))
    20.  
    21.         {
    22.             currentTexture++;
    23.             currentTexture %= textures.Length;
    24.             GetComponent<Renderer>().material.mainTexture = textures[currentTexture];
    25.         }
    26.  
    27.     }
    28. }
    29.  
    30.  
    So above script does exactly what I want. I just want to use an UI button instead of the spacebar :)
     
  2. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325
  3. s096268

    s096268

    Joined:
    Oct 28, 2015
    Posts:
    11
    Cool this already helped out! Now I'm able to change the materials through a UI button click :) Thing is, the movie (set as material) won't play anymore. I do have a 'play movie script' on the object though:

    Code (csharp):
    1.  
    2.  
    3. using UnityEngine;
    4. using System.Collections;
    5.  
    6. public class PlayMovie : MonoBehaviour {
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.  
    11.         MovieTexture movie = GetComponent<Renderer>().material.mainTexture as MovieTexture;
    12.         movie.Play();
    13.         movie.loop = true;
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void Update () {
    18.    
    19.     }
    20. }
    21.  
    22.  
    If I just assign a material - with a movie assigned to it - to the object it works perfectly well. However when the material is changed with the UI button, the script doesn't start the movies anymore.

    Any thoughts on this?
     
  4. s096268

    s096268

    Joined:
    Oct 28, 2015
    Posts:
    11
    Nevermind, I think I got this! Of course I need to put my code in the void update, otherwise it won't load when the material is changed :)