0
\$\begingroup\$

I have a script main.cs which creates a prefabricated button based on this SO post. I thought btnController.cs was providing the methods for the Button created in main.cs? Why would it have a casting issue?

Error

Assets/scripts/main.cs(21,51): error CS0030: Cannot convert type `UnityEngine.UI.Button' to `btnController'

main.cs

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

public class main : MonoBehaviour {

    public Button myButtonPrefab;

    // Use this for initialization
    void Start () {
        createButton ("minion");
    }

    // Update is called once per frame
    void Update () {

    }

    //this is giving a button prefab all the methods from the class btnController
    void createButton(string name){
        btnController b = ((btnController)Instantiate(myButtonPrefab));
        b.Setup(name,0);
    }
}

btnController.cs

using UnityEngine;
using System.Collections;

public class btnController : MonoBehaviour {
    string name="";
    int value=0;

    public void Setup(string n, int v){
        name = n;
        value = v;
    }

    void OnClick(){
        Debug.Log("btn clicked");
    }
}
\$\endgroup\$
1
\$\begingroup\$

Instantiate will always give you an object. The better way to do that is first convert it in GameObject then access your script from there.

GameObject go = Instantiate (myButtonPrefab) as GameObject;
btnController bc = go.GetComponent<btnController>();
bc.Setup(name,0);

It is for when your prefab has already btnController attached.

If you want to add script, do that as,

btnController bc = go.AddComponent<btnController>();
bc.Setup(name,0);
\$\endgroup\$
  • \$\begingroup\$ Can you clarify why that is 'the better way'? I'd arguably say that having it as the componenttype you are trying to access is much more preferable. The only reason this wasn't working was because he had a type mismatch between Button and btnController. \$\endgroup\$ – Athos vk Jan 23 '16 at 7:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.