Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
20
Question by Aldofi · Mar 17, 2010 at 06:52 PM · materialassign

How can I assign materials using C# code?

I'm trying to assign a material in the Project to a gameobject I create by code. My question is how can I do that directly instead of creating a new Material, asign a shader, textures, etc.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image duck ♦♦ · Mar 17, 2010 at 08:12 PM 0
Share

Do you mean create a new material from code, or just assign? Your question body & title seem to suggest one and the other respectively.

avatar image Aldofi · Mar 22, 2010 at 04:40 PM 0
Share

I mean creating a new material from code, but I already have the answer, thanks

5 Replies

· Add your reply
  • Sort: 
avatar image
41
Best Answer

Answer by duck · Mar 17, 2010 at 08:11 PM

You can set or change the material of an existing GameObject (if the GameObject has a renderer), using the Renderer.material property, like this:

 GetComponent<Renderer>().material = newMaterialRef;

Of course using this method means that you need a reference to an existing material, so you need to create one in your Assets (Library) first, and then reference it in your script. You can do this by creating a public variable of type 'Material' like this:

public Material newMaterialRef;

And then dragging a reference of the new material into that variable slot in the inspector.

If you want to create a new material from scratch in code, you can do that too. To do this, you can just create a new Material object like this:

Material myNewMaterial = new Material( shader );

Where 'shader' is a reference to an existing shader to use. The example given in the manual here also has an example where a new shader is created at the same time, from source code included as text.

Hope this is enough to get you started. If you have more specific questions, feel free to ask as a comment to this answer!

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DaveA · Jul 28, 2010 at 08:34 PM 4
Share

Same basic question, but I want to script the part where you 'drag a reference of the new material into that variable slot' - I want to grab an existing material from my assets and assign it all via script.

avatar image jwinn · Jun 19, 2016 at 02:41 AM 4
Share

An update for those using the latest versions of Unity. Using "renderer.material = new$$anonymous$$aterialRef;" will cause an error about this being obsolete. This is because you must now access the Renderer component. C# example:

 Renderer rend = GetComponent<Renderer>();
 if (rend != null){
     rend.material = new$$anonymous$$aterialRef;
 }

And it's best not to GetComponent every loop; see the linked docs page for an example that stores the component reference on Start().

avatar image Xenocide jwinn · Feb 02, 2017 at 11:20 PM 0
Share

If anyone is wondering why this code isn't working for them, just swap the first line of code around. So: GetComponent(); = new$$anonymous$$aterialRef;

That's what also worked for me, if anyone is having any further problems!

avatar image
51

Answer by MSylvia · Sep 14, 2010 at 05:21 PM

Using a material that has already been creaded and using it at runtime without dragging it in the inspector can be done with Resources.Load. Within your Asstest folder you will have to create a Resources folder and place your material there.

// Assigns a material named "Assets/Resources/DEV_Orange" to the object.
Material newMat = Resources.Load("DEV_Orange", typeof(Material)) as Material;
gameObject.renderer.material = newMat;
Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MattLebrao · May 14, 2018 at 01:32 PM 0
Share

$$anonymous$$eep in $$anonymous$$d that Resources.Load() loads na asset at runtime, and is not as fast as instancing a prefab already instantiated somewhere in the scene. If you absolutely must use Resources.Load() you must manage it as to not load the same resource twice, or unload it after every use (non-optimal in most cases).

avatar image BPR · May 14, 2018 at 02:00 PM 1
Share

Also be $$anonymous$$dfull that a material which is referenced only in code and not in scene might get stripped from a build.

avatar image MattLebrao BPR · May 14, 2018 at 04:43 PM 1
Share

True, but not in this case since it's located in the special "Resources" folder. What one might want to pay attention to is the fact that assets in the resources folder will be included in the build whether it's used by the game or not.

avatar image elyeschine · Dec 04, 2019 at 06:59 PM 1
Share

very heplful ! newer versions of unity will ask to convert the third line to :

gameObject.GetComponent<Renderer>().material = new$$anonymous$$at;

avatar image
7

Answer by bharath09vadde · Jun 08, 2018 at 09:02 AM

If somebody is searching for this answer recently. This might be useful

     public GameObject box;
     public Material red;
     private void OnTriggerEnter(Collider other)
     {
          if (other.gameObject.tag == "Pickupable")
          {
               box.GetComponent<Renderer>().material = red;
          }
     }



Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by firestorm185 · Jul 29, 2020 at 09:41 PM

What if your model has more than one material slot? I have a robot hand with two materials that I need to swap via code. (I appreciate any answers ahead of time, ya'll rock)

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image dehv · Aug 02, 2020 at 04:35 PM 1
Share

I had this problem today as well and the solution is that you need to create an array of materials and assign it to the renderer after that. $$anonymous$$y code looks something like this:

$$anonymous$$eshRenderer renderer = gameObject.GetComponent(); $$anonymous$$aterial[] materials = new $$anonymous$$aterial[renderer.shared$$anonymous$$aterials.Length]; for (int i = 0; i < renderer.shared$$anonymous$$aterials.Length; i++) { materials[i] = my$$anonymous$$aterial; } renderer.shared$$anonymous$$aterials = materials;

I need every $$anonymous$$aterial to be the same $$anonymous$$aterial, but you could make the array manually and choose different ones for the different slots

avatar image
1

Answer by LtKelleyUSMC · Jun 01 at 03:42 AM

Maybe someone want to explain what is up with this $$anonymous$$ stuff. I see this type of thing all the time. It appears to me, that the developer of this website, needs to allow for this, because this $$anonymous$$ stuff makes the comment almost totally unreadable, or perhaps the person making the comment DOES NOT KNOW how to post the comment (really??? How about that). Seems to me this comment says: MeshRenderer renderer = gameObject.GetComponent(); Material[] materials = new Material[renderer.sharedMaterials.Length; etc, etc, etc One can determine that $$anonymous$$ is replacing the M, but why does anyone want to spend time thinking this way? I thought the point was to find answers to questions, and not go thru this SPELLING CRAPOLA

 $$anonymous$$eshRenderer renderer = gameObject.GetComponent(); $$anonymous$$aterial[] materials = new $$anonymous$$aterial[renderer.shared$$anonymous$$aterials.Length]; for (int i = 0; i < renderer.shared$$anonymous$$aterials.Length; i++) { materials[i] = my$$anonymous$$aterial; } renderer.shared$$anonymous$$aterials = materials;

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MattLebrao · Jun 01 at 05:57 AM 1
Share

I don't even know what this is, this seems to be new to me. What causes this anonymous thing?

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

13 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to assign transfrom array in the code? 1 Answer

Add a texture onto a material 3 Answers

Mass assign shaders? 1 Answer

I have problem, i cant spawn enemies with script Waypoints. 2 Answers

Beginner: assigning texture to part of GameObject 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges