- Home /
ALWAYS GET CS0120: Changing material of an object in a script
If my terminology or anything is off I apologise and hope you know what I'm talking about:
No matter what I try I just cannot get this to work despite doing exactly what Im told in many tutorials
I simply want to change the material of an object to a certain material based on a variable i have set up, but I always get the error message: CS0120: An object reference is required to access non-static member.
This is one of my simpler attempts:
public Texture WarriorBD;
public Texture MageBD;
public Texture RogueBD;
private void SetBackdrop(int jobSelection){
if (jobSelection == 0) {
Renderer.material.SetTexture("CCBackdrop", WarriorBD);
}else if(jobSelection == 1) {
Renderer.material.SetTexture("CCBackdrop", MageBD);
}else if(jobSelection == 2) {
Renderer.material.SetTexture("CCBackdrop", RogueBD);
}
}
I then call 'SetBackdrop' in another script, which has worked with methods with the same structure as this.
The variable 'jobSelection' isnt an issue as it works in these other methods.
"CCBackdrop" is the name of the object I wish to change the material for.
The public textures sometimes pop up in the inspector panel and I can assign textures to them, but sometimes they don't turn up even when the script is identically written (but I don't think it is related to this problem)
Please tell me what I'm doing wrong and/or how I might do want I'm trying to do.
for the object I will attach the script to. Is this not how to do it?
Answer by Positive7 · Jul 17, 2015 at 09:08 PM
public Texture WarriorBD;
public Texture MageBD;
public Texture RogueBD;
private void SetBackdrop(int jobSelection){
if (jobSelection == 0) {
GetComponent <Renderer>().material.SetTexture("CCBackdrop", WarriorBD);
}else if(jobSelection == 1) {
GetComponent <Renderer>().material.SetTexture("CCBackdrop", MageBD);
}else if(jobSelection == 2) {
GetComponent <Renderer>().material.SetTexture("CCBackdrop", RogueBD);
}
}
Thank you Positive7, but with this code I get the error
CS0103: The name `GetComponent' does not exist in the current context for lines 7, 9 and 11
Am I missing a namespace or something?
Yes. Your entire code needs to be wrapped in a class, and you need to use the UnityEngine namespace. These should have already been included in your code template when you created a new C# file from the Unity editor though...
I found why GetComponent wasnt working:
using UnityEngine; using System.Collections;
public class CharacterCreationFunctions {
I wasn't inheriting from monobehavior. Thats what it needed
Your answer
![](https://koobas.hobune.stream/wayback/20220611231630im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Drawing a display panel with textures. 1 Answer
Light based texture change on material 0 Answers
Multiple Cars not working 1 Answer
Howto save ProceduralTexture as PNG 2 Answers
Help with understanding UV's in script created mesh 0 Answers