Serialize a string without (Instance)

Hello guys, I got a little problem, I’m trying to workaround Unity unability to serialize Materials, and I figured I could do it with strings and material names.
Except when serializing a string, Unity always add (Instance) at the end of the name and thus it fuck up my name so when I try call it, I get the ugly pink material error.

In short:

  • My material is named skin1
  • I push save button
  • Unity save the name as “skin1 (Instance)” in the file
  • I try load it, it doesn’t work because I ask for a name like “skin1” and it return “skin1 (Instance)”

My script is like so

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    
    public class Manager : MonoBehaviour {
    
    	public BinaryFormatter bf;
    
    	// Use this for initialization
    	void Start () {
    	
    	}
    	
    	// Update is called once per frame
    	void Update () {
    	
    	}
    
    	public void Saving(){
    
    		SavedData dataa = new SavedData();
    		dataa._skin = GameObject.Find("skin").GetComponent<Renderer>().material.name;
    		//dataa._hair = GameObject.Find("hair").GetComponent<Renderer>().material;
    		//dataa._wings = GameObject.Find("hair").GetComponent<Renderer>().material;
    
    		BinaryFormatter bf = new BinaryFormatter();
    		FileStream file = File.Create (Application.persistentDataPath + "/savedGames.json");
    		bf.Serialize(file, dataa);
    		file.Close();
    
    
    	}
    
    	public void Loading(){
    
    		print("clack" + Application.persistentDataPath);
    
    		if(File.Exists(Application.persistentDataPath + "/savedGames.json")) {
    			BinaryFormatter bf = new BinaryFormatter();
    			FileStream file = File.Open(Application.persistentDataPath + "/savedGames.json", FileMode.Open);
    			SavedData dataa = (SavedData)bf.Deserialize(file);
    
    			print("clack" + dataa._skin);
    			GameObject.Find("skin").GetComponent<MeshRenderer>().material = (Material)Resources.Load(dataa._skin, typeof(Material));
    
    			file.Close();
    		}
    			
    	}
    }

And this is my Serializable class

using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

[Serializable]

public class SavedData{

	public string _skin;

}

it’s incredibly annoying, since I got a lot of elements to save thus, and I got no idea how to remove that (Instance) in the name. Anyone can help?

Use MeshRenderer.sharedMaterial instead of just .material. Whenever you use the not shared version, you force unity to create a new instance, hence why you get “(instance)” in the name. It is also less efficient.