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

Setting Textures on multiple objects via script

Discussion in 'Scripting' started by Volcanicus, Apr 29, 2019.

  1. Volcanicus

    Volcanicus

    Joined:
    Jan 6, 2018
    Posts:
    169
    All the search results I got were from 2012 and earlier and most of them are deprecated.
    I am trying to set a texture to 200 game objects using a simple class however I am having a hard time accessing the appropriate component.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor;
    5.  
    6. public class SM_Bld_Texture
    7. {
    8.     [MenuItem("Tools/Assign BLD Texture")]
    9.     public static void AssignTileMaterial()
    10.     {
    11.         GameObject[] tiles = GameObject.FindGameObjectsWithTag("SM_Bld");
    12.  
    13.         Texture texture = Resources.Load<Texture>("T_PolygonTown_01_A");
    14.  
    15.         foreach (GameObject t in tiles)
    16.         {
    17.             t.GetComponent<MeshRenderer>().material.SetTexture("T_PolygonTown_01_A", texture);
    18.  
    19.         }
    20.     }
    21. }
    I am a bit at a loss... am I even accessing the right component?
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    If all your tiles share same material, it should be enought to

    Code (CSharp):
    1. t.GetComponent<MeshRenderer>().sharedMaterial.SetTexture("T_PolygonTown_01_A", texture);
    For any single tile. Note that .sharedMaterial i've used instead of .matrerial in your code.
     
  3. Volcanicus

    Volcanicus

    Joined:
    Jan 6, 2018
    Posts:
    169
    Perfect, thank you very much :)