Set own script as a dependency to a text component
Hi, i have a script that should be add to every ui text component automaticaly.
How can i do that?
Answer by DoTA_KAMIKADzE · Oct 04, 2015 at 12:44 AM
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).
Option 2 seems to be what I'm looking for, but I do not know how to do that.
If you mean how to modify then look at v#1 and just do that directly with Text class ins$$anonymous$$d of creating ImprovedText.
If you mean how to purchase source code license from Unity then just contact sales person (same can be found on Get Unity page under Enterprise tab). I guess the pricing is figured out depending on various aspects, and probably it is not cheap, though TBH I don't know even approximate numbers (you can ask for example Nexon, but then again I guess it's under NDA), and I don't really think that you want source code license just for that, if I were you I'd go for v#1.
Ok, thats a little oversized. Some Guidelines will hopefully do it. Thanks for all the help.