Hi, I have a script that puts a few GUIText objects on to the screen at Start. For each one I am having to set its Font, Material and FontSize amongst other things. For the elements that stay the same, this feels too repetitive. I know I could declare a method that automates this process and then passes the variables to each GUItext object upon call, but I’m not sure how to start the method.
I tried doing
public GUIText TextProperties(GUIText textGUI, Vector2 myOffset, int myFontSize, Vector2 textOffset)
{
textGUI.guiText.font = pipFont;
textGUI.guiText.fontSize = myFontSize;
textGUI.guiText.material = textMaterial;
textOffset = textGUI.guiText.pixelOffset;
textOffset.x = textGUI.guiText.pixelOffset.x + myOffset.x;
textOffset.y = textGUI.guiText.pixelOffset.y + myOffset.y;
textGUI.guiText.pixelOffset = textOffset;
}
where textGUI is declared upon method call,
but it doesn’t seem to work.
For this you should use prefabs.
Read what they are:
http://unity3d.com/support/documentation/Manual/Prefabs.html
Then how to instantiate (create) them:
http://unity3d.com/support/documentation/Manual/Instantiating%20Prefabs.html
Here is an edit for you:
File #1:
GUITextPlus.cs:
// Attach this file to a GameObject, and make a prefab out of it
using UnityEngine;
using System.Collections;
[System.Serializable]
public class GUITextConfig
{
public Font font;
public int fontSize;
public Material material;
public GUITextConfig(Font font, int fontSize, Material material)
{
this.fontSize = fontSize;
this.font = font;
this.material = material;
}
}
[RequireComponent (typeof (GUIText))]
public class GUITextPlus : MonoBehaviour
{
public void Initialize(GUITextConfig initData)
{
guiText.font = initData.font;
guiText.fontSize = initData.fontSize;
guiText.material = initData.material;
}
}
File #2:
GUITextManager.cs:
// Attach this file to a game object, drag the prefab you created above to the
// "prefabWithGUITextPlus" slot.
// Next step up as many GUITextConfig sets as you need (first number of total such
// elements and then the define/drag in the inspector your desired data.
using UnityEngine;
using System.Collections;
public class GUITextManager : MonoBehaviour
{
public GUITextPlus prefabWithGUITextPlus;
public GUITextConfig[] guiTextSets;
void Start()
{
foreach(GUITextConfig guiTextSet in guiTextSets)
{
GUITextPlus gtext = Instantiate(prefabWithGUITextPlus) as GUITextPlus;
gtext.Initialize(guiTextSet);
}
}
}