Error using methods on a new instantiated prefab

I am trying to Instantiate a prefab when clicking a button, and the change some properties and use some methods on the instantiated object, but I think I’m missing something since I’m getting the following message:

InvalidCastException: Cannot cast from source type to destination type.
GUIMain.OnGUI () (at Assets/Scripts/GUIMain.cs:42)

Meaning that I missed some cast or I’m using the wrong object. This is my code:

public MoveUnit1 unit;

void Start () {

void OnGUI () {
    if (GUI.Button (new Rect (0,Screen.height - Screen.height/4, Screen.width, Screen.height/4), "Invoke") {
    GameObject u = (GameObject)Instantiate(unit, unit.transform.position, unit.transform.rotation);

The “u” object is supposed to be an object that haves a script called MoveUnit1, with a method setFireRate(float f).
What I’m doing wrong here?

Instantiate returns the same object as the type of the first argument. As you are passing in a MoveUnit1, it will return a MoveUnit1.

Two options to solve

  • Change the type of MoveUnit1 to a GameObject
  • Cast the type of u and the casting to MoveUnit1