Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Change Texture Problem

Discussion in 'Scripting' started by mediagr, Sep 28, 2016.

  1. mediagr

    mediagr

    Joined:
    Feb 16, 2016
    Posts:
    14
    Hello my friends.

    I want your help!!!
    I found a tutorial for Texture Swap but it doesn't work.
    My textures is at folder Texture.
    Error: NullReferenceException: Object reference not set to an instance of an object
    test1.Update () (at Assets/test1.cs:20)

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class test1 : MonoBehaviour
    5. {
    6.     public Texture[] textures;
    7.     public int currentTexture;
    8.     private Renderer rend;
    9.  
    10.     void Start (){
    11.     }
    12.  
    13.  
    14.     void Update ()
    15.     {
    16.         if(Input.GetKeyDown(KeyCode.E))
    17.         {
    18.             currentTexture++;
    19.             currentTexture %= textures.Length;
    20.             rend.material.mainTexture = textures [currentTexture];
    21.         }
    22.     }
    23. }
     
  2. Vedrit

    Vedrit

    Joined:
    Feb 8, 2013
    Posts:
    514
    rend is not being set anywhere, so it is null
     
  3. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    This should fix it:
    Code (CSharp):
    1. void Start()
    2. {
    3.           rend = gameObject.GetComponent<Renderer>();
    4. }
     
  4. hurimoran95

    hurimoran95

    Joined:
    May 25, 2020
    Posts:
    1
    current texture%= textures.Length;
    why it helps me to keep the var in the array limits?