- Home /
Is it possible to find all objects that reference a specific texture during run time?
I have a project with multiple objects using the same texture. For example purposes let say "Big_Car_Red" is the texture name. In a C# script, I want to find all the objects that reference that specific texture. The reason I need this is to change all the objects that use that texture to another similar texture, like "Big_Car_Blue." Is there a way I can find all the objects that referenced "Big_Car_Red" during run time? I'd prefer to do this without looping through every object in the scene.
If the objects all have the same material on them you could change the textures by something like
$$anonymous$$aterial m_material = oneOfYourCars.GetComponent().shared$$anonymous$$aterial;
m_material.mainTexture = newTextureForAllCars;
I get that, but I think you missed my question. I'm looking for all Objects my current texture is being used by, so I can change them all to my new texture.
Changing the shared material does this: it changes the texture of all objects which have this material at once.
Answer by UsmanAbbasi · Jan 11, 2016 at 01:21 PM
Find all objects in scene which have "Image" component and then iterate all of them to check which objects have image named "Big_Car_Red" and replace it with "Big_Car_Blue".
Image[] textures = FindObjectsOfType(typeof(Image)) as Image[];
for( int i = 0 ; i < textures.Length ; i++)
{
if(textures[i].sprite.name == "Big_Car_Red")
{
textures[i].sprite = Resources.Load<Sprite>("Big_Car_Blue");
}
}
P.S: Make sure to include "using UnityEngine.UI" in file where you write this code as "Image" class is placed in "UnityEngine.UI" namespace. Also place image named "Big_Car_Blue" in "Resources" folder and set its import type to "Sprite".
This is close to what I looking for. I was looking for something similar to AssetDatabase.GetDependencies(...) to call during run time. The problem with your answer, It's a big game. Looping through all objects that have an "Image" component may take too much time.
Yes if your scene is big then it will take time. I am not sure about AssetDatabase.GetDependencies() thing. Never used it.
Your answer
Follow this Question
Related Questions
Ref to Texture Missing when Creating Sprite by Script during Asset Postprocessing 1 Answer
Unity3D: objeec 1 Answer
Unity Trees Material/Texture changed 0 Answers
Changing texture on prefab at runtime (c#) 1 Answer
Lightmaps/objects and textures 2 Answers