- Home /
Instantiate new Gui Button from code
If I try
Button instance = (Button)UnityEngine.Object.Instantiate(x);
I get:
InvalidCastException: Cannot cast from source type to destination type.
Any ideas? Why I cannot clone a Button? See attached image, the Watch window shows some strange Values.
clipboard01.jpg
(52.9 kB)
Comment
Best Answer
Answer by gerleim · Jan 02, 2015 at 07:00 PM
All right, I don't know why, because the old method should work also, here's how to fix it:
// works
Button buttonPrefab = UnityEngine.Resources.Load<Button>("UI/Button");
Button instance = (Button)UnityEngine.Object.Instantiate(buttonPrefab);
// doesn't work: InvalidCastException: Cannot cast from source type to destination type.
Button buttonPrefab2 = (Button)UnityEngine.Resources.Load("UI/Button");
Button instance2 = (Button)UnityEngine.Object.Instantiate(buttonPrefab);
Your code gives me error: "The thing you want to instantiate is null.".
Your answer

Follow this Question
Related Questions
Can't add reference resolution on Canvas 1 Answer
[Unity 4.6] Button Tracking UI System? 0 Answers
(c#) Photon networking, get players in room? 1 Answer
4.6 UI Text rect does not expand automatically 2 Answers
Unity 4.6 button movement problem 1 Answer