- Home /
Material changes when i drag and drop it on object but doesnt through code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class swaptexture : MonoBehaviour {
public gemlife g;
public Material[] mats;
private Renderer rend;
// Use this for initialization
void Start () {
rend = GetComponent<Renderer> ();
rend.sharedMaterial = mats [0];
}
// Update is called once per frame
void Update () {
if (g.ratio >= 0.96f)
rend.sharedMaterial = mats [1];
}
}
when i drag and drop the materials on my player it works but when i use this script it doesnt. yes the condition is being met and code is working fine and i can also see the material changing inside the inspector but it doesnt reflect to my player :(
Ins$$anonymous$$d of shared$$anonymous$$aterial
, have you tried material
?
Answer by IgorAherne · Dec 27, 2016 at 04:23 PM
Your code seems fine.
I would debug it through breakpoints or you could also test out with several debug.Log()
Check Update is called
Check the name of this.gameObject
check the name of rend.sharedmaterial
check all the names in mats[]
check the name of rend.sharedmaterial.shader
check the name of shaders in mats[]
try changing color in mats[1], then debug the color of rend.sharedmaterial = mats[1]
i already confirmed that the update is being called since the condition is being met and moreover i can also see the material being changed in the inspector during runtime when the condition was met but for some reason it didnt reflect on my player. although when i drag and drop the same material on my player directly it works fine.
Also, there might be several shared materials per model. What might happen is you could have 1 material for the body, and another for a tiny peice like belt-buckle. Try seeing how many shared materials you have (most likely there is an array), then assign your mats[1] into the correct slot of rend.sharedmaterials[]
https://docs.unity3d.com/ScriptReference/Renderer-shared$$anonymous$$aterials.html
i only have one single texture for the whole body so there are only two of them: one is blue outfit and the other is yellow. the main problem here is that the material gets added to the object and it shows that it is changing inside the inspector but it NEVER GETS APPLIED to my object. i want the exact behavior which i get when i drag and drop that texture on my player...
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Flip over an object (smooth transition) 3 Answers