- Home /
How do I change the material of a prefab when it is not in the hierarchy?
Hey, I am building an AR app using AR Foundation but got stuck with changing the material of my model during runtime by pressing a button.
The script below works perfectly fine when I attach it to my model and then create buttons with OnClick() Events to access the specific material WHEN my model is in the hierarchy.
But I don't want it to stay in the hierarchy because otherwise it will constantly show up in AR. If I remove it from the hierarchy, the OnClick() is obviously missing a prefab.
So I need to have the possibility to still change materials from button clicks but without my model staying in the hierarchy. I think "AddListener" could be a solution, but I don't really know how to edit the script in order to make it work. With AddListener I wouldn't have to use OnClick().
Can anyone please show me the solution?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeColor : MonoBehaviour
{
public Material[] material;
Material setMaterial;
Renderer rend;
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled=true;
}
void Update()
{
}
public void GreyMaterial()
{
rend.sharedMaterial = material[0];
setMaterial = rend.material;
}
public void YellowMaterial()
{
rend.sharedMaterial = material[1];
setMaterial = rend.material;
}
public void RedMaterial()
{
rend.sharedMaterial = material[2];
setMaterial = rend.material;
}
}