Search Unity

[SOLVED] "Type Mismatch" in a simple public property

Discussion in 'Scripting' started by syscrusher, Sep 13, 2020.

  1. syscrusher

    syscrusher

    Joined:
    Jul 4, 2015
    Posts:
    1,104
    I have some very simple code that's malfunctioning cosmetically in the Inspector but working fine behind the scenes.

    Here's a simplified version:

    Code (CSharp):
    1. public class MyClass : MonoBehaviour {
    2.   public Material material;
    3.  
    4.   public void Initialize() {
    5.     if (material == null) {
    6.       material = new Material(Shader.Find("PathToMyShader"));
    7.     }
    8.   }
    9. }
    10.  
    11. [CustomEditor(typeof(MyClass)]
    12. public class MyClassEditor : Editor {
    13.  
    14.   private MyClass myTarget;
    15.   private Material mat;
    16.  
    17.   public void OnInspectorGUI() {
    18.     myTarget = target as MyClass;
    19.     base.OnInspectorGUI();
    20.     if (GUILayout.Button("Manual Initialize")) {
    21.       myTarget.Initialize();
    22.     }
    23.   }
    24. }
    Now, here's the puzzle: That material gets properly initialized and is used elsewhere in my code, does exactly what it's supposed to do. But in the inspector, the material field displays empty (as it should) until the first time I press the Manual Initialize button, after which it displays as "Type Mismatch" even though the actual value of the field is clearly correct.

    I'm clearly overlooking some stupidly simple thing here, but I could use a fresh pair of eyes to help me spot the mistake. Anyone see it? Thanks!
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    References in the inspector are to physical assets. Such as a prefab, material in the project folder, or something in the scene. You cannot store a reference to something which only exists in memory and has not been serialized.
     
    Suh1ee and pKallv like this.
  3. syscrusher

    syscrusher

    Joined:
    Jul 4, 2015
    Posts:
    1,104
    That's exactly it -- thanks! As I suspected, the problem is something I knew but which just slipped my mind.

    The only reason I made that member public was to expose it in the inspector for debugging -- it doesn't normally need to be changed by the user. I'll just mark it private, since I now know it's working.

    Call this one solved, and I raise a virtual glass in your honor.
     
    Kurt-Dekker likes this.
  4. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    Solved my problem, thanks.