- Home /
Creating GUITexture with a reference
I need to create a guitexture but maintain a reference to it, so that I can change the layer, position, size and the like. Currently I am trying to do this with the following code:
GUITexture g =(GUITexture)GUITexture.Instantiate(live,new Vector3(xStart+spacing*i,yStart),Quaternion.identity);
However this creates the following error:
InvalidCastException: Cannot cast from source type to destination type. Lives.Start () (at Assets/Scripts/Lives.cs:19)
It is important to note that when the section of code is changed to just:
GUITexture.Instantiate(live,new Vector3(xStart+spacing*i,yStart),Quaternion.identity);
It correctly creates a GUItexture, but there is no reference, meaning I can not do what I need to.
What is the correct way to create a GUItexture, and store it in a variable?
If you need more information please do not hesitate to ask. Thank you for your help.
I am running windows 8.1, on unity 4.5of6, in a 2d project.
SOLUTION:
The solution to my issue was to save it into a variable as a game object, but to also access the GUITexture via getComponent().
Answer by aldonaletto · Jul 05, 2014 at 07:50 PM
It's C#, thus you must cast the type (see the end of this line):
GUITexture g = Instantiate(live, new Vector3(xStart+spacing*i,yStart),Quaternion.identity) as GUITexture;
or
GUITexture g = (GUITexture)Instantiate(live, new Vector3(xStart+spacing*i,yStart),Quaternion.identity);
Instantiate returns type Object, not GUITexture. JS handles this for you, but C# doesn't - the C# compiler complains about everything it can.
I would like to apologize, I posted the code and error from an old version of my project, in which I had indeed forgotten to cast. I am sorry for wasting your time, but I have updated my question to ask what I truly meant to. Thank you for your help.
Your answer
Follow this Question
Related Questions
GUITexture not showing on Instantiate 1 Answer
GUI problem: Lack of Events and Listeners. 1 Answer
Show GUI Texture on Trigger and Instantiate Object if Button pressed while In Trigger? 1 Answer
Reduce Draw call for Multiple GUI Textures with same Texture 1 Answer
Button then instanitates gameobject 1 Answer