Hi,
i have a script that should be add to every ui text component automaticaly.
How can i do that?
Hi,
i have a script that should be add to every ui text component automaticaly.
How can i do that?
Variant #1 - inherit:
Create ImprovedText:
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(CustomScript))] //auto add your CustomScript
public class ImprovedText : Text
{
}
Though you most likely will want to add some menu items as well, so here is example for those:
using UnityEngine;
using UnityEngine.UI;
[AddComponentMenu("UI/ImprovedText")]//Add to Component menu
[RequireComponent(typeof(CustomScript))]
public class ImprovedText : Text
{
}
rest can be done through editor script:
#if UNITY_EDITOR
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
public sealed class PrefabCreator : Editor
{
private static Vector2 defaultPos { get { return new Vector2(0, 0); } }
[MenuItem("GameObject/UI/ImprovedText", false, 10)]//Add to GameObject menu
[MenuItem("Improved Components/Improved UI/ImprovedText")]//or create custom menu item
private static void CreateImprovedText()
{
GameObject newTxt = new GameObject("New ImprovedText", typeof(ImprovedText));
newTxt.layer = LayerMask.NameToLayer("UI");
// newTxt.AddComponent<CustomScript>(); //this is another workaround for RequireComponent, that will work only when this function is called
newTxt.transform.position = defaultPos;
}
}
#endif
you can even add custom Editor script that will check if your component has your script component and if it doesn’t then do something (for more information about Editor scripts check out API, Manual and Tutorials).
Variant #2 - purchase Unity source code license and modify it (Text component) instead of inheriting.
Variant #3 - EditorApplication.hierarchyWindowChanged, use example from the link, then just loop through objects, detect if object with Text component was added - if yes then add your script to it as well (check variant #1 - it contains example on how to add component from script).