Problem with removing materials

Hi, im making a gameobject that can be outlined when clicked, but filter the way im filtering out the outline material(via name(i checked and the name matches with the material i want to remove)) is not working and i need help, thanks.

using System.Collections;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using UnityEditor.SearchService;
using UnityEngine;
using UnityEngine.Assertions.Must;
using UnityEngine.Rendering;
using UnityEngine.UI;
using UnityEngine.UIElements;

public class Click : MonoBehaviour
{
    public GameObject[] highlightable;
    void Start()
    {
        if (GameObject.FindGameObjectsWithTag("Clickable Object") != null)
        {
            highlightable = GameObject.FindGameObjectsWithTag("Clickable Object");
        }
        Unclicked();
    }
    void Update()
    {

    }
    void Unclicked()
    {
        foreach (GameObject gameObject in highlightable)
        {
            Material[] tempMats;
            tempMats = gameObject.GetComponent<MeshRenderer>().materials;
            for (int i=0;i == tempMats.Length;i++)
            {
                if (tempMats[i].name == "Outline Material")
                {
                    tempMats[i] = null;
                }
            }
            gameObject.GetComponent<MeshRenderer>().SetMaterials(materials: tempMats.ToList());
        }
    }
}

1 Answer

1

You have a bunch of issues in your code again.

  1. When iterating an array you want to use:
 i < tempMats.Length 

not

 i == tempMats.Length 
  1. There is no function called “SetMaterials” in the MeshRenderer, that I can find.
    You need to just assign the tempMats back into the materials array:
gameObject.GetComponent<MeshRenderer> ().materials = tempMats;
  1. As soon as you access the materials, Unity creates instances of the materials, so the materials will now have the name of “Some Material (Instance)”. So you can’t check if the material.name == "Outline Material" anymore.
    You should use:
 if (material.name.Contains("Outline Material"))

It mostly worked, but unity replaced the new mat texture withe the no texture texture, thanks ,btw

–

"It mostly worked, but unity replaced the new mat texture withe the no texture texture". I have no clue what this means. What new mat?

–

the other material in the game object, i looked at the mesh renderer and confirmed that it applied it, but it just didnt render

–

It applied what? Your code is only setting a material slot to null, which means no material.

–

Yea, but it also broke the material i wanted to keep and didnt set to null

–