"Type mismatch" in play mode after doing member assignment


In my program there is a script that adds to the model different kind of guns. It is made by creating custom editor script. So I instantiate in Editor mode a prefab. And then I run the game with guns attached. The problem is when I set the target to the first of guns the next gun already has that target due to what I am seeing in Debug mode(using breakpoints). I suppose this is not true however, because if you look in the editor, you will see that all instantiated prefabs have target == null and prefab itself has target == type mismatch.

What is that ?

Thank you!


Some code… But there is nothing interesting in that…

    // TurretControl.cs
    public void SetTarget(GameObject go)
		if (go == null)
		Debug.Log("Before:" + target);
		target = go;
		Debug.Log("After:" + target);

The log looks like this(for 3 guns):

Before: null
After: someValue
Before: someValue
After: someValue
Before: someValue
After: someValue

I checked that “go” points to the correct target. However the prefab of gun will have target == type mismatch and the clones of that prefab (that should be changed) have target == null


I created a simple project that represents the issue. Some description here:

  • Click on the prefab in the prefabs folder and see that target public variable is null. Switch into the play mode and right click on the cube. Watch again in the prefab target variable it should become “type mismatch” and GunPrefab(Clone) that is in Slot1 remains the same!
  • See attachment below.

I found your bug!

To find it, follow these steps:

1: open your example project, click the Root object, and select “Set Weapons”.

2: select the GunPrefab(Clone) in the Hireachy (the one that’s instantiated), and ensure that the target variable of the GunControl script is set to nothing (null).

3: rename the GunPrefab(Clone) object to something else. I chose ThisWillShowTheError.

4: go to the GunControl script, and edit Update and SetTarget to be this:

// Update is called once per frame
void Update()
    if (Input.GetKeyDown(KeyCode.D))
        Debug.Log(this + " has target " + target);

public void SetTarget(GameObject go)
    Debug.Log(this + "Sets target to: " + go);
    target = go;

5: Go into play mode. First right click the cube, and then click ‘D’.

Your output will be this:

GunPrefab (GunControl)Sets target to: Cube (UnityEngine.GameObject)

ThisWillShowTheError (GunControl) has target null

Do you get it?