Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Discussion Can't add .mtl materials to prefabs

Discussion in 'Prefabs' started by anab99, Mar 17, 2023.

  1. anab99

    anab99

    Joined:
    Feb 14, 2023
    Posts:
    1
    Hi all,

    I wanted to add materials for .obj files. First of all, I turned the obj files into prefabs in order to import them into my scene. Then, I wanted to add the specific materials to it from their respective .mtl file. I used the following code and it loads the prefabs but not the materials to it. Can someone help, please?
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class loadPrefabs : MonoBehaviour
    {

    void Start()
    {
    UnityEngine.Object[] prefabObjects = Resources.LoadAll("Prefabs", typeof(GameObject));
    Material [] mat_s = Resources.LoadAll("Materials", typeof(Material)) as Material[];
    foreach (UnityEngine.Object prefabObject in prefabObjects)
    {
    GameObject prefab = (GameObject)prefabObject;
    string prefabName = prefab.name;
    Debug.Log(prefab.name);
    GameObject newPrefab = Instantiate(prefab, Vector3.zero, Quaternion.identity);
    Renderer renderer = newPrefab.GetComponent<Renderer>();
    foreach (var mat in mat_s) {
    if (mat.name == name)
    renderer.material=mat;
    }

    }

    }
    }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,761