- Table of contents
- Changing color of UI Text in Unity into custom values
- Change color of text during runtime (Unity)?
- Rich Text
- Text.text
Changing color of UI Text in Unity into custom values
I want the title to change its text and color based on the object that is mouse-overed. The script below is added to each object that is intended to change the color and text …
public Text title; void OnMouseEnter() { switch(name) { CONDITION1: title.color = Color.yellow; // works well break; CONDITION2: title.color = new Color(254f, 152f, 203f); // doesn't work break; } title.text = name; } void OnMouseExit() { title.text = "DEFAULT VALUE"; title.color = Color.white; }
title.color = new Color(254.0f/255.0f, 152.0f/255.0f, 203.0f/255.0f);
title.color = new Color32(254, 152, 203, 255);
Change color of text during runtime (Unity)?
Well if you want to change R,G,B or A components of the color of the text you can do it this way: Public Text text; float r=0.2f,g=0.3f,b=0.7f,a=0.6f; void Start () { …
Public Text text; float r=0.2f,g=0.3f,b=0.7f,a=0.6f; void Start() { text=gameobject.GetComponent<Text>(); text.color= new Color(r,g,b,a); }
public Text myText;
myText.color = Color.green; myText.text = "Enter anything, will display in UI Text";
using UnityEngine; using UnityEngine.UI; using System.Collections; public class test : MonoBehaviour { public Text text; void Start () { text = gameObject.GetComponent<Text> (); text.color = Color.white; } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class ColorDemo : MonoBehaviour { [SerializeField] Text infoText; void Start () { infoText.text = "Hello World"; infoText.color = Color.red; //Red color using Color class //Red color using hex value. (255,0,0) => 255/255, 0/255, 0/255) => (1,0,0) infoText.color = new Color(1f, 0f, 0f); // Color with opacity value. 1 means opaque and 0 means transparent. infoText.color = new Color(1f, 0f, 0f, 0.5f); } }
/ Ctrl+H»,
WMDHorizontalRule: «Horizontal Rule Ctrl+R»,
WMDUndo: «Undo — Ctrl+Z»,
WMDRedoWin: «Redo — Ctrl+Y»,
WMDRedoOther: «Redo — Ctrl+Shift+Z»,
WMDHelp: «Markdown Help»,
draftMessage: «We noticed that you were previously working on TYPO. What would you like to do now?»,
draftSaveMessage: «Saving Draft…»,
draftLoadButton: «Load Draft»,
draftDeleteButton: «Delete Draft»,
linkMenuInsertLink: «Insert link»,
linkMenuEditLink: «Edit link»,
linkMenuUnlink: «Remove link»,
linkMenuAnchor: «Anchor»,
linkMenuMailto: «Email»,
inputTextPrompt: «Text»,
inputWebPrompt: «URL»,
inputLinkNewTab: «Open link in a new tab»,
inputImageForm: «Update Image»,
inputImageTitle: «Title»,
inputImagePosition: «Position»,
inputImagePositionNone: «None»,
inputImagePositionLeft: «Left»,
inputImagePositionRight: «Right»,
formattingLabel: «Formatting»,
formattingParagraph: «Normal Text»,
formattingQuote: «Quote»,
formattingCode: «Code»,
formattingHeader: «Header»,
formattingBold: «Bold»,
formattingItalic: «Italic»,
formattingUnderline: «Underline»,
formattingFontColor: «Font Color»,
formattingBackColor: «Back Color»,
formattingIndent: «Indent»,
formattingOutdent: «Outdent»,
formattingAlignment: «Alignment»,
formattingAlignLeft: «Align text to the left»,
formattingAlignCenter: «Center text»,
formattingAlignRight: «Align text to the right»,
formattingAlignJustify: «Justify text»,
formattingHorizontalRule: «Insert Horizontal Rule»,
toolTipsInsertImage: «Insert Image»,
toolTipsInsertFile: «Insert File»,
toolTipsInsertCode: «Insert Code»,
toolTipsInsertVideo: «Insert Video»,
toolTipsInsertTable: «Insert Table»,
toolTipsorderedList: «Ordered List»,
toolTipsunorderedList: «Unordered List»,
toolTipLink: «Link»,
tableInsert: «Insert Table»,
tableRows: «Rows»,
tableColumns: «Columns»,
tableInsertRowAbove: «Add Row Above»,
tableInsertRowBelow: «Add Row Below»,
tableInsertColumnLeft: «Add Column Left»,
tableInsertColumnRight: «Add Column Right»,
tableDelete: «Delete Table»,
tableDeleteColumn: «Delete Column»,
tableDeleteRow: «Delete Row»,
tableAddHead: «Add Header»,
tableDeleteHead: «Delete Header»,
uploadOrChoose: «Or Choose»,
uploadDropFileHere: «Drop file here»,
uploadFilenameOptional: «Name (optional)»,
emailValidationPrompt: «Resend validation email»,
emailValidationPromptBody: «Do you want to resend email validation?»,
invalidReputation: «Error: You must enter a valid Integer without commas.»
},
url: {
login: «/users/login.html»,
register: «/users/register.html»,
getRevision: «/revisions/get-revision.json»,
getComments: «/comments/%25ID%25/list.json»,
uploadFile: «/uploadFile.html»,
uploadProgress: «/uploadProgress.json»,
uploadPreview: «/uploadPreview.html»,
cropUpload: «/cropUpload.json»,
cancelUpload: «/cancelUpload.json»,
markdownHelp: «/static/markdown/help.html»,
updateMarkdown: «/commands/updateMarkdown.json»,
profile: «/users/{id}/{plug}.html»,
extractKeywords: «/extract-keywords.json»,
follow: «/follow/%7BobjId%7D/%7Btype%7D.json»,
unfollow: «/unfollow/%7BobjId%7D/%7Btype%7D.json»,
getUserFollows: «/%7Buser%7D/getUserFollows.json»,
condensedProfileUrl: «/users/%7Buser%7D/condensedProfile.json»,
viewTopicJSON: «/topics/%7Btopic%7D/view.json»,
topicIcon: «/topics/%7Btopic%7D/icon.html»,
topic: «/topics/%7Btopic%7D.html»,
topicSearch: «/search/topics.json»,
awardListUrl: «/badge/%7BawardType%7D/%7Bdesc%7D.json»,
usersSearch: «/users/list.json»,
usersLookup: «/users/lookup.json»,
mentionsSearch: «/users/mentionsSearch.json»,
searchJson: «/search.json»,
trackJs: «/static/trackJs.json»,
userAvatar: «/users/%7BuserId%7D/photo/view.html»,
revisionView: «/revisions/{nodeId}.html»
},
extraScripts: {
jcrop: {
js: ‘/themes/thub/scripts/jcrop/js/jquery.Jcrop.js’,
css: ‘/themes/thub/scripts/jcrop/css/jquery.Jcrop.css’
}
},
options: {
maxTopics: ‘5’,
gravatarEnabled: true
},
additional: {«recaptchaKey»:»6LdgnSUUAAAAAAqL8W_eR-OFMVywBpdvXECfMXtd»,»TH_CSRF»:»a-7924730642105088252″},
useRelativeTime: true,
userRealName: false
};
pageContext.i18n[«delete»] = «Delete»;
(function ($) {
«use strict»;
$.extend($.fn.select2.defaults, {
formatNoMatches: function () {
return ‘No matches found’;
},
formatInputTooShort: function (input, min) {
var n = min — input.length;
if (n == 1) {
return ‘Please enter 1 more character.’;
}
else {
var return_str = «Please enter $n more characters.»;
return return_str.replace(«$n», n.toString());
}
},
formatInputTooLong: function (input, max) {
var n = input.length — max;
if (n == 1)
return ‘Please delete 1 character.’;
else {
var return_str = ‘Please delete $n characters.’;
return return_str.replace(«$n», n.toString());
}
},
formatSelectionTooBig: function (limit) {
if (limit == 1)
return ‘You can only select 1 item.’;
else {
var return_str = ‘You can only select $n items.’;
return return_str.replace(«$n», limit.toString());
}
},
formatLoadMore: function (pageNumber) {
return ‘Loading more results…’;
},
formatSearching: function () {
return ‘Searching…’;
}
});
})(jQuery);
$(document).ready(function(){pageContext.options.commentsAttachmentsEnabled = true});
$(document).ready(function(){
commands[«convertToComment»].onSuccess = function(data) {
setTimeout(function(){
commandUtils.reloadPage(); //wait 1 second before reloading
}, 1000);
};
});
window.dataLayer = window.dataLayer || [];
if(window.location.pathname === «/users/register.html») {
window.location.href=»https://id.unity.com/account/new»;
}
function OptanonWrapper() { }
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: ‘dataLayer-initialized’,
GenesisID: undefined // undefined if user is not logged. if it is logged pass Genesis ID value, something like ‘3573726253193’
});
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({‘gtm.start’:
new Date().getTime(),event:’gtm.js’});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!=’dataLayer’?’&l=’+l:»;j.async=true;j.src=
‘https://www.googletagmanager.com/gtm.js?id=’+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,’script’,’dataLayer’,’GTM-5V25JL6′);
$(function () {
pageContext.i18n.modTalk = ‘moderation talk’;
pageContext.i18n.replyToComment = ‘Reply’;
pageContext.i18n.modTalkEmpty = ‘moderation talk is empty’;
pageContext.url.getModTalk = «/comments/%25ID%25/listModTalk.json»;
pageContext.url.possibleCommentRecipients = «/comments/%ID%/possibleRecipients.json»;
pageContext.url.commentEdit = ‘/comments/%25ID%25/edit.html’;
pageContext.url.commentView = ‘/comments/%ID%/view.html’;
pageContext.i18n.commentVisibility = {
‘full’: ‘Viewable by all users’,
‘op’: ‘Viewable by the original poster’,
‘mod’: ‘Viewable by moderators’,
‘opAndMod’: ‘Viewable by moderators and the original poster’,
‘other’: ‘Advanced visibility’,
‘dialogTitle’: ‘Comment visibility’,
‘selectGroups’: ‘Visible to groups’,
‘selectOther’: ‘Other recipients’,
‘selectOriginalPoster’: ‘Original poster’,
‘selectModerators’: ‘Moderators’,
‘selectAssignees’: ‘Asked to answer users’
};
pageContext.i18n.commentMenuLabels = {
‘comment-edit’: ‘comments.menu.edit’,
‘comment-delete’: ‘comments.menu.delete’,
‘comment-convert’: ‘comments.menu.convert’
};pageContext.i18n.answer= {
bestAnswer: ‘Best Answer’,
controlBar : {
accept: ‘Accept’,
unaccept: ‘Unaccept’,
acceptCommand: ‘Accept this answer as correct’,
cancelAcceptedCommand: ‘Remove this answers accepted status’
}
};
window.croles = {
u: false, op: false, m: false,
og: false, as: false, ag: false,
dc: false, doc: false, eo: false, ea: false
};
tools.init({
q: {
e: false, ew: false, eo: false,
r: false, ro: false,
d: false, dow: false, fv: false,
c: false, co: false,
p: false, tm: false
, ms: false, mos: false
},
n: {
f: false, vf: false, vfo: false,
vr: false, vro: false,
c: false, co: false,
vu: false, vd: false,
w: false, wo: false,
l: false
},
c: {
e: false, eo: false,
d: false, dow: false,
ta: false, tao: false,
l: false
},
a: {
e: false, ew: false, eo: false,
d: false, dow: false,
a: false, aoq: false, ao: false,
tc: false, tco: false,
p: false, tm: false
},
pc: croles
}, {
tc: true,
nsc: false
});
commandUtils.initializeLabels();
});
Products
Solutions
Made with Unity
Learning
Support & Services
Community
Asset Store
Get Unity
(function(){ var cx = ‘002645370080425984202:i_d7wpkpdzy’; var gcse = document.createElement(‘script’); gcse.type = ‘text/javascript’; gcse.async = true; gcse.src = (document.location.protocol == ‘https:’ ? ‘https:’ : ‘http:’) + ‘//www.google.com/cse/cse.js?cx=’ + cx; var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(gcse, s); })();
UNITY ACCOUNT
You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio.
Login
Create account
Blog
Forums
Answers
Evangelists
User Groups
Beta Program
Advisory Panel
var submore = ‘More’;
(function(){ var cx = ‘002645370080425984202:i_d7wpkpdzy’; var gcse = document.createElement(‘script’); gcse.type = ‘text/javascript’; gcse.async = true; gcse.src = (document.location.protocol == ‘https:’ ? ‘https:’ : ‘http:’) + ‘//www.google.com/cse/cse.js?cx=’ + cx; var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(gcse, s); })();
Navigation
Home
Products
Solutions
Made with Unity
Learning
Support & Services
Community
Blog
Forums
Answers
Evangelists
User Groups
Beta Program
Advisory Panel
Unity account
You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio.
Login
Create account
Language
Chinese
Spanish
Japanese
Korean
Portuguese
$(document).ready(function () {
// var ie7 = $.browser.msie && $.browser.version
Right click Canvas, got to UI, add a Text element. On this text element click on add component and under UI select button. You now have a button script attached to your text …
Ctrl+K", WMDImage: "Image Ctrl+G", WMDAttachment: "Attachment Ctrl+U", WMDOrderedList: "Numbered List Ctrl+O", WMDUnorderedList: "Bulleted List Ctrl+U", WMDHeading: "Heading / Ctrl+H", WMDHorizontalRule: "Horizontal Rule Ctrl+R", WMDUndo: "Undo - Ctrl+Z", WMDRedoWin: "Redo - Ctrl+Y", WMDRedoOther: "Redo - Ctrl+Shift+Z", WMDHelp: "Markdown Help", draftMessage: "We noticed that you were previously working on TYPO. What would you like to do now?", draftSaveMessage: "Saving Draft...", draftLoadButton: "Load Draft", draftDeleteButton: "Delete Draft", linkMenuInsertLink: "Insert link", linkMenuEditLink: "Edit link", linkMenuUnlink: "Remove link", linkMenuAnchor: "Anchor", linkMenuMailto: "Email", inputTextPrompt: "Text", inputWebPrompt: "URL", inputLinkNewTab: "Open link in a new tab", inputImageForm: "Update Image", inputImageTitle: "Title", inputImagePosition: "Position", inputImagePositionNone: "None", inputImagePositionLeft: "Left", inputImagePositionRight: "Right", formattingLabel: "Formatting", formattingParagraph: "Normal Text", formattingQuote: "Quote", formattingCode: "Code", formattingHeader: "Header", formattingBold: "Bold", formattingItalic: "Italic", formattingUnderline: "Underline", formattingFontColor: "Font Color", formattingBackColor: "Back Color", formattingIndent: "Indent", formattingOutdent: "Outdent", formattingAlignment: "Alignment", formattingAlignLeft: "Align text to the left", formattingAlignCenter: "Center text", formattingAlignRight: "Align text to the right", formattingAlignJustify: "Justify text", formattingHorizontalRule: "Insert Horizontal Rule", toolTipsInsertImage: "Insert Image", toolTipsInsertFile: "Insert File", toolTipsInsertCode: "Insert Code", toolTipsInsertVideo: "Insert Video", toolTipsInsertTable: "Insert Table", toolTipsorderedList: "Ordered List", toolTipsunorderedList: "Unordered List", toolTipLink: "Link", tableInsert: "Insert Table", tableRows: "Rows", tableColumns: "Columns", tableInsertRowAbove: "Add Row Above", tableInsertRowBelow: "Add Row Below", tableInsertColumnLeft: "Add Column Left", tableInsertColumnRight: "Add Column Right", tableDelete: "Delete Table", tableDeleteColumn: "Delete Column", tableDeleteRow: "Delete Row", tableAddHead: "Add Header", tableDeleteHead: "Delete Header", uploadOrChoose: "Or Choose", uploadDropFileHere: "Drop file here", uploadFilenameOptional: "Name (optional)", emailValidationPrompt: "Resend validation email", emailValidationPromptBody: "Do you want to resend email validation?", invalidReputation: "Error: You must enter a valid Integer without commas." }, url: { login: "/users/login.html", register: "/users/register.html", getRevision: "/revisions/get-revision.json", getComments: "/comments/%25ID%25/list.json", uploadFile: "/uploadFile.html", uploadProgress: "/uploadProgress.json", uploadPreview: "/uploadPreview.html", cropUpload: "/cropUpload.json", cancelUpload: "/cancelUpload.json", markdownHelp: "/static/markdown/help.html", updateMarkdown: "/commands/updateMarkdown.json", profile: "/users/{id}/{plug}.html", extractKeywords: "/extract-keywords.json", follow: "/follow/%7BobjId%7D/%7Btype%7D.json", unfollow: "/unfollow/%7BobjId%7D/%7Btype%7D.json", getUserFollows: "/%7Buser%7D/getUserFollows.json", condensedProfileUrl: "/users/%7Buser%7D/condensedProfile.json", viewTopicJSON: "/topics/%7Btopic%7D/view.json", topicIcon: "/topics/%7Btopic%7D/icon.html", topic: "/topics/%7Btopic%7D.html", topicSearch: "/search/topics.json", awardListUrl: "/badge/%7BawardType%7D/%7Bdesc%7D.json", usersSearch: "/users/list.json", usersLookup: "/users/lookup.json", mentionsSearch: "/users/mentionsSearch.json", searchJson: "/search.json", trackJs: "/static/trackJs.json", userAvatar: "/users/%7BuserId%7D/photo/view.html", revisionView: "/revisions/{nodeId}.html" }, extraScripts: { jcrop: { js: '/themes/thub/scripts/jcrop/js/jquery.Jcrop.js', css: '/themes/thub/scripts/jcrop/css/jquery.Jcrop.css' } }, options: { maxTopics: '5', gravatarEnabled: true }, additional: {"recaptchaKey":"6LdgnSUUAAAAAAqL8W_eR-OFMVywBpdvXECfMXtd","TH_CSRF":"a-7924730642105088252"}, useRelativeTime: true, userRealName: false }; pageContext.i18n["delete"] = "Delete"; input[type="password"] { font-family: Arial; } (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return 'No matches found'; }, formatInputTooShort: function (input, min) { var n = min - input.length; if (n == 1) { return 'Please enter 1 more character.'; } else { var return_str = "Please enter $n more characters."; return return_str.replace("$n", n.toString()); } }, formatInputTooLong: function (input, max) { var n = input.length - max; if (n == 1) return 'Please delete 1 character.'; else { var return_str = 'Please delete $n characters.'; return return_str.replace("$n", n.toString()); } }, formatSelectionTooBig: function (limit) { if (limit == 1) return 'You can only select 1 item.'; else { var return_str = 'You can only select $n items.'; return return_str.replace("$n", limit.toString()); } }, formatLoadMore: function (pageNumber) { return 'Loading more results...'; }, formatSearching: function () { return 'Searching...'; } }); })(jQuery); $(document).ready(function() { var $style; $style = $(':before,:after{content:none !important}'); $('head').append($style); return setTimeout((function() { return $style.remove(); }), 0); }); $(document).ready(function(){pageContext.options.commentsAttachmentsEnabled = true}); $(document).ready(function(){ commands["convertToComment"].onSuccess = function(data) { setTimeout(function(){ commandUtils.reloadPage(); //wait 1 second before reloading }, 1000); }; }); window.dataLayer = window.dataLayer || []; if(window.location.pathname === "/users/register.html") { window.location.href="https://id.unity.com/account/new"; } function OptanonWrapper() { } window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'dataLayer-initialized', GenesisID: undefined // undefined if user is not logged. if it is logged pass Genesis ID value, something like '3573726253193' }); (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-5V25JL6'); $(function () { pageContext.i18n.modTalk = 'moderation talk'; pageContext.i18n.replyToComment = 'Reply'; pageContext.i18n.modTalkEmpty = 'moderation talk is empty'; pageContext.url.getModTalk = "/comments/%25ID%25/listModTalk.json"; pageContext.url.possibleCommentRecipients = "/comments/%ID%/possibleRecipients.json"; pageContext.url.commentEdit = '/comments/%25ID%25/edit.html'; pageContext.url.commentView = '/comments/%ID%/view.html'; pageContext.i18n.commentVisibility = { 'full': 'Viewable by all users', 'op': 'Viewable by the original poster', 'mod': 'Viewable by moderators', 'opAndMod': 'Viewable by moderators and the original poster', 'other': 'Advanced visibility', 'dialogTitle': 'Comment visibility', 'selectGroups': 'Visible to groups', 'selectOther': 'Other recipients', 'selectOriginalPoster': 'Original poster', 'selectModerators': 'Moderators', 'selectAssignees': 'Asked to answer users' }; pageContext.i18n.commentMenuLabels = { 'comment-edit': 'comments.menu.edit', 'comment-delete': 'comments.menu.delete', 'comment-convert': 'comments.menu.convert' };pageContext.i18n.answer= { bestAnswer: 'Best Answer', controlBar : { accept: 'Accept', unaccept: 'Unaccept', acceptCommand: 'Accept this answer as correct', cancelAcceptedCommand: 'Remove this answers accepted status' } }; window.croles = { u: false, op: false, m: false, og: false, as: false, ag: false, dc: false, doc: false, eo: false, ea: false }; tools.init({ q: { e: false, ew: false, eo: false, r: false, ro: false, d: false, dow: false, fv: false, c: false, co: false, p: false, tm: false , ms: false, mos: false }, n: { f: false, vf: false, vfo: false, vr: false, vro: false, c: false, co: false, vu: false, vd: false, w: false, wo: false, l: false }, c: { e: false, eo: false, d: false, dow: false, ta: false, tao: false, l: false }, a: { e: false, ew: false, eo: false, d: false, dow: false, a: false, aoq: false, ao: false, tc: false, tco: false, p: false, tm: false }, pc: croles }, { tc: true, nsc: false }); commandUtils.initializeLabels(); }); Products Solutions Made with Unity Learning Support & Services Community Asset Store Get Unity (function(){ var cx = '002645370080425984202:i_d7wpkpdzy'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); UNITY ACCOUNT You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account Blog Forums Answers Evangelists User Groups Beta Program Advisory Panel var submore = 'More'; (function(){ var cx = '002645370080425984202:i_d7wpkpdzy'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); Navigation Home Products Solutions Made with Unity Learning Support & Services Community Blog Forums Answers Evangelists User Groups Beta Program Advisory Panel Unity account You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account Language Chinese Spanish Japanese Korean Portuguese $(document).ready(function () { // var ie7 = $.browser.msie && $.browser.version Ask a question Spaces Default Help Room META Moderators Topics Questions Users Badges Home / var jsonTopicSearch = '/search/topics.json'; var retagUrl = '/commands/940456/editQuestionTopics.json'; function submit_retag() { $.post(retagUrl, $("#topics_retag_container").serializeArray(), function (data) { document.location.reload(); }); } function setup_retag() { $("#topics_retag_container").css("display", "inline"); // $("#topics_retag_container").show(); $("#id_tags_container").hide(); $("#topics_retag").select2({ placeholder: 'Enter topics...', minimumInputLength: 1, width: "250px", ajax: { url: jsonTopicSearch, dataType: 'json', data: function (term, page) { return { q: term }; }, results: function (data, page) { for (var i = 0; i .question-body, .node-body { min-height: 50px; } .answer-body, .reply-body { min-height: 115px; } 5 Question by mlepage · Apr 04, 2015 at 10:49 PM · guibuttontextcolorhover How to change text color on hover in new GUI? Using Unity 5 GUI, suppose I want text only menu buttons. I make buttons with text children and disable the button's image script, so the button background does not draw, I see text only as desired. However, the colors (normal, highlighted, pressed, disabled) do not apply to the text color. They seem to apply only to the image, which I disabled. How can I have the text color change when the button UI is manipulated? Comment Add comment $(function() { $('#reply-link-940456').click(function() { commandUtils.showMessage('', "You must log in to post comments."); return false; }); }); · Show 1 10 |3000 characters needed characters left characters exceeded ▼ Viewable by all users Viewable by moderators Viewable by moderators and the original poster Advanced visibility Viewable by all users mlepage · Apr 04, 2015 at 10:50 PM 0 Share Also a bit of a meta comment: there needs to be a sticky FAQ thingy explaining which tags to use for old GUI stuff vs. new GUI stuff. Too convoluted, too hard to search. $(function () { setupComments($('#question-container-940456'), true, false, croles, "full", false) }); $(document).ready(function () { var $question = $("#question-container-940456"); var $replyLink = $question.find(".reply-link"); $replyLink.click(function (e) { e.preventDefault(); $question.find(".add-comment-link").click(); }); $(".ajax-command").click(function () { $('.dropdown-toggle').dropdown('toggle'); }); }) 10 Replies · Add your reply Sort: 3 Best Answer Answer by lordlycastle · Apr 04, 2015 at 11:34 PM You can do by scripting, but that’s just painful. You should rather watch this video. It tells you how to create transitions when hovering over, or clicking etc an UI element. Comment Add comment $(function() { $('#reply-link-940486').click(function() { commandUtils.showMessage('', "You must log in to post comments."); return false; }); }); · Show 1 · Share 10 |3000 characters needed characters left characters exceeded ▼ Viewable by all users Viewable by moderators Viewable by moderators and the original poster Advanced visibility Viewable by all users mlepage · Apr 05, 2015 at 02:25 PM 0 Share O$$anonymous$$ that video seems to be the best way to do it, thanks. $(function () { setupComments($('#answer-container-940486'), true, false, croles, "full", true) }); $(document).ready(function () { var $answer = $("#answer-container-940486"); var $replyLink = $answer.find(".reply-link"); $replyLink.click(function (e) { e.preventDefault(); $answer.find(".add-comment-link").click(); }); }); 19 Answer by jcv8000 · Apr 04, 2015 at 11:27 PM You could use the button to receive the mouse hover. Add this script to each of the buttons: using UnityEngine; using System.Collections; using UnityEngine.EventSystems; using UnityEngine.UI; public class MenuButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { public Text theText; public void OnPointerEnter(PointerEventData eventData) { theText.color = Color.red; //Or however you do your color } public void OnPointerExit(PointerEventData eventData) { theText.color = Color.white; //Or however you do your color } }
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; using UnityEngine.UI; [RequireComponent (typeof(Button))] public class MenuButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler { Text txt; Color baseColor; Button btn; bool interactableDelay; void Start () { txt = GetComponentInChildren<Text>(); baseColor = txt.color; btn = gameObject.GetComponent<Button> (); interactableDelay = btn.interactable; } void Update () { if (btn.interactable != interactableDelay) { if (btn.interactable) { txt.color = baseColor * btn.colors.normalColor * btn.colors.colorMultiplier; } else { txt.color = baseColor * btn.colors.disabledColor * btn.colors.colorMultiplier; } } interactableDelay = btn.interactable; } public void OnPointerEnter (PointerEventData eventData) { if (btn.interactable) { txt.color = baseColor * btn.colors.highlightedColor * btn.colors.colorMultiplier; } else { txt.color = baseColor * btn.colors.disabledColor * btn.colors.colorMultiplier; } } public void OnPointerDown (PointerEventData eventData) { if (btn.interactable) { txt.color = baseColor * btn.colors.pressedColor * btn.colors.colorMultiplier; } else { txt.color = baseColor * btn.colors.disabledColor * btn.colors.colorMultiplier; } } public void OnPointerUp (PointerEventData eventData) { if (btn.interactable) { txt.color = baseColor * btn.colors.highlightedColor * btn.colors.colorMultiplier; } else { txt.color = baseColor * btn.colors.disabledColor * btn.colors.colorMultiplier; } } public void OnPointerExit (PointerEventData eventData) { if (btn.interactable) { txt.color = baseColor * btn.colors.normalColor * btn.colors.colorMultiplier; } else { txt.color = baseColor * btn.colors.disabledColor * btn.colors.colorMultiplier; } } }
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; using UnityEngine.UI; using TMPro; [RequireComponent( typeof( Button ) )] public class FullyReactiveButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler { private TextMeshProUGUI txt; private Button btn; public Color normalColor; public Color disabledColor; public Color pressedColor; public Color highlightedColor; void Start() { txt = GetComponentInChildren<TextMeshProUGUI>(); btn = gameObject.GetComponent<Button>(); } private ButtonStatus lastButtonStatus = ButtonStatus.Normal; private bool isHighlightDesired = false; private bool isPressedDesired = false; void Update() { ButtonStatus desiredButtonStatus = ButtonStatus.Normal; if ( !btn.interactable ) desiredButtonStatus = ButtonStatus.Disabled; else { if ( isHighlightDesired ) desiredButtonStatus = ButtonStatus.Highlighted; if ( isPressedDesired ) desiredButtonStatus = ButtonStatus.Pressed; } if ( desiredButtonStatus != this.lastButtonStatus ) { this.lastButtonStatus = desiredButtonStatus; switch ( this.lastButtonStatus ) { case ButtonStatus.Normal: txt.color = normalColor; break; case ButtonStatus.Disabled: txt.color = disabledColor; break; case ButtonStatus.Pressed: txt.color = pressedColor; break; case ButtonStatus.Highlighted: txt.color = highlightedColor; break; } } } public void OnPointerEnter( PointerEventData eventData ) { isHighlightDesired = true; } public void OnPointerDown( PointerEventData eventData ) { isPressedDesired = true; } public void OnPointerUp( PointerEventData eventData ) { isPressedDesired = false; } public void OnPointerExit( PointerEventData eventData ) { isHighlightDesired = false; } public enum ButtonStatus { Normal, Disabled, Highlighted, Pressed } }
Rich Text
7 rows · <color=cyan>some text</color> The available color names are given in the table below. material: This is only useful for text meshes and renders a section of text with a …
GUIStyle style = new GUIStyle (); style.richText = true; GUILayout.Label("<size=30>Some <color=yellow>RICH</color> text</size>",style);
Text.text
Use this to access or edit the message displayed in Text. Use other Text properties such as size, font, and alignment to change the appearance of the text. These properties modify the text in …
using UnityEngine; using UnityEngine.UI;// UI.Text.text example // // A Space keypress changes the message shown on the screen. // Two messages are used. // // Inside Awake a Canvas and Text are created.public class Example : MonoBehaviour { private enum UpDown { Down = -1, Start = 0, Up = 1 }; private Text text; private UpDown textChanged = UpDown.Start; void Awake() { // Load the Arial font from the Unity Resources folder. Font arial; arial = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf"); // Create Canvas GameObject. GameObject canvasGO = new GameObject(); canvasGO.name = "Canvas"; canvasGO.AddComponent<Canvas>(); canvasGO.AddComponent<CanvasScaler>(); canvasGO.AddComponent<GraphicRaycaster>(); // Get canvas from the GameObject. Canvas canvas; canvas = canvasGO.GetComponent<Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; // Create the Text GameObject. GameObject textGO = new GameObject(); textGO.transform.parent = canvasGO.transform; textGO.AddComponent<Text>(); // Set Text component properties. text = textGO.GetComponent<Text>(); text.font = arial; text.text = "Press space key"; text.fontSize = 48; text.alignment = TextAnchor.MiddleCenter; // Provide Text position and size using RectTransform. RectTransform rectTransform; rectTransform = text.GetComponent<RectTransform>(); rectTransform.localPosition = new Vector3(0, 0, 0); rectTransform.sizeDelta = new Vector2(600, 200); } void Update() { // Press the space key to change the Text message. if (Input.GetKeyDown(KeyCode.Space)) { if (textChanged != UpDown.Down) { text.text = "Text changed"; textChanged = UpDown.Down; } else { text.text = "Text changed back"; textChanged = UpDown.Up; } } } }
Next Lesson PHP Tutorial
N0pe_ 0 / 0 / 0 Регистрация: 09.07.2016 Сообщений: 19 |
||||
1 |
||||
Изменение цвета текста скриптом14.07.2016, 09:03. Показов 33755. Ответов 2 Метки нет (Все метки)
Суть в том, что при определённых обстоятельствах цвет текста должен изменяться, чего таки мне добиться не удалось.
__________________
0 |
103 / 90 / 19 Регистрация: 15.04.2015 Сообщений: 353 |
|
15.07.2016, 13:40 |
2 |
Просто не работает? Никаких ошибок не выскакивает? Вы уверены, что ваши OnMouseUp и OnMouseDown вызываются?
0 |
vlad1988_1 0 / 0 / 0 Регистрация: 04.01.2017 Сообщений: 1 |
||||
04.01.2017, 19:39 |
3 |
|||
У меня работает:
0 |
$begingroup$
There are a few objects in the scene as well as a title. I want the title to change its text and color based on the object that is mouse-overed. The script below is added to each object that is intended to change the color and text of the title.
The title changes it’s color correctly when values like Color.red
are assigned but doesn’t change color when values like new Color(254f, 152f, 203f)
.
public Text title;
void OnMouseEnter()
{
switch(name)
{
CONDITION1:
title.color = Color.yellow; // works well
break;
CONDITION2:
title.color = new Color(254f, 152f, 203f); // doesn't work
break;
}
title.text = name;
}
void OnMouseExit()
{
title.text = "DEFAULT VALUE";
title.color = Color.white;
}
Is there a specific reason to the former method to work and latter not to work? How can I change the color of the Text
element with custom values?
asked Jan 13, 2015 at 8:25
VaraquilexVaraquilex
8473 gold badges12 silver badges26 bronze badges
$endgroup$
$begingroup$
Constructor of Color class takes float parameters from 0 to 1 like this title.color = new Color(1f, 0.5f, 0.8f);
answered Jan 13, 2015 at 8:30
nexxnexx
2362 silver badges5 bronze badges
$endgroup$
2
$begingroup$
You can do this with the code below:
title.color = new Color(254.0f/255.0f, 152.0f/255.0f, 203.0f/255.0f);
answered Sep 15, 2015 at 10:06
$endgroup$
1
$begingroup$
If you’d like to pass RGBA in the common way you can also use Color32 that takes 4 bytes ranged from 0 — 255:
title.color = new Color32(254, 152, 203, 255);
answered Jan 30, 2018 at 14:29
$endgroup$
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
Today we discuss about some e question regarding Text Mesh Pro like
What is Text Mesh Pro in unity?
Advantages of using Text Mesh Pro?
You will see how to use Text Mesh Pro is an example?
How to use Text Mesh Pro in a 3D Game?
How to create a custom font asset in Text Mesh Pro?
How to create a glow effect in unity?
How to outline and shadow effect in Text.
You will learn the Text Mesh Pro with a step by step guide.+
Text Mesh Pro Introduction:
- In Unity 2019.4 TextMesh Pro is available by default.
- TextMesh Pro is the ultimate text solution for Unity.
- It provides so many features for text formatting and your layouts. It’s very flexible during text styling and texturing.
- you can create 2D/3D fonts with effects in the TextMesh Pro.
- you can use the TextMesh Pro as UI Text Element and also as a 3D game object.
Text Mesh Pro Demo
Open unity hub and create a new unity project with a 3D template.
TextMesh Pro as 3D Object
- In Hierarchy Window, create a new 3D text object as below.
- If you are using TextMesh Pro for the first time in the current project then you see popup box about TextMesh Import settings as below
- Import TMP Essentials(useful library and class).
- Also, Import the example files of TextMesh Pro
- TextMesh Pro Package imported in the root folder.
- Now you have 3D Text as 3D object.
Create a 3D Environment in scene.
Change Directional Light Color to White.
Add a 3d object – plane in the current scene and rename it as “Ground”.
Set properties of “Ground” object as below.
Create a new folder with name “Materials”.
Create a new material for the Ground object in the Materials folder.
Change the material name as “Ground_Material”.
Change the material properties as below.
Open Lighting setting menu from the window menu
Adjust Lighting window with Inspector window.
Change properties of Environment lighting for better lighting condition.
Change the color of the ground material as below
Add a 3d cube object in the current scene.
rename this cube object as “Player”.
Create a material for the Player Object and rename it as “Player_Material”.
Change properties of Player_Material as below image.
Create a new material for the skybox in Materials folder.
Assign a new skybox material in lighting settings.
Output after scene setup.
- Rename the TextMesh Pro text as “Name_TMP_Text” in the hierarchy window.
- Change the width and the height of Name_TMP_Text as below.
Properties of the TextMesh Pro Text component
- Change the properties of the TextMesh Pro Text component of the Name_TMP_Text as below.
Change Text Input
- If RTL Editor is enabled then you can write in reverse order.
- Text Input Box: Here you can type text which will be rendered. You can write multiple lines here. you can use special characters & Rich Text tags like
- n – new line
- t – tab
- <b>Bold</b>
- <i>Italics</i>
- <u>Underline</u>
- <s>Strikethrough</s>
- <sup>Superscript</sup>
- <sub>Subscript</sub>
- <size=48>Point size 48</size>
- <size=+18>Point size increased by 18</size>
- <size=-18>Point size decreased by 18</size>
- <pos=5.5>Characters positioned about 5.5 characters from left side. <color=yellow>Yellow text</color>
Change font style
- here you see that Font style applied on text.
- Font Style : applies different font styles like Bold, Italic, Underline, Lowercase, Uppercase, Smallcaps, etc…
Change Font Size
- if you want to adjust your text as per the Text component’s width and height, enable the Auto Size feature as below.
Change Vertex Color
- Apply color on each character in the text.
- here word “Player” did not change its color because we set the color tag in Text Input Field. Note: Vertex Color was not applied to the character which has the color tag.
Change Color Gradient
- By default this property is disabled.
- If you enable this property then it will show you more sub-properties as in the image below
Here you can select already created color gradient from the “Color Present” field or you create your own gradient using the Color Mode & the Colors field.
- Let’s select one gradient color from the Color Present Field as below image
Output :
Here you notice that Vertex color + Color Gradient mix together so give another color.
Color of Player word not changed due to color tag.
How to create own customize gradient color for TextMesh Pro Text
- Remove the Color Preset and select Color Mode property.
- choose the color mode from the list.
- set Vertex Color as white.
- Now you see the original gradient color.
Override Tags
By default this property is disabled. If you enable this property then you will get output like
Now you notice that the Player Word also changes into the new gradient color. it means if you enable the “Override Tags” property then colors which you applied by tag in the Text Input Box will no longer work, as they are overridden.
Spacing Options
- Spacing Option Property is used to set space between two words or lines or characters or even paragraphs.
- Here we change the text and Spacing option to understand its process.
Alignments
- It will control the alignment of the text. Options are Left, Center, Right, and Justified. When Justified is selected, the ratio controls how additional spacing is added between words and characters.
Wrapping
- It wraps text to the next line when reaching the edge of the container.
Example:
Wrapping – Enable
Wrapping – Disable
Overflow
- It will provide ways to display text which past edge of the container.
- example: if we select Ellipsis type then the extra text will be display as (… ellipses) format.
Mapping
Mapping is used to map characters or words or lines or whole paragraphs with shader. We will discuss later in shader topics.
Extra Settings
- Margins – space between text and text container.
- Sorting in Layer – when we work with many texts, it helps in sorting.
- Order in Layer – A higher number means higher priority Here In the image, we add another text in the scene and set different color modes and order in the layer so the second text sets the front side of the first text.
- Remove the second text.
- Orthographic Mode – It is useful when you are working with an orthographic camera.
- Rich Text – It will enable the use of Rich Tags like <font>, <color> in TextMesh text otherwise rich tags will not work and it looks like normal text.
Example:
Rich Text = disabled
Rich Text = enabled
- Parse Escape Character – If enabled then “n” works as escape character otherwise just a simple Text.
- Extra Padding – it will add extra padding between the characters and the edge of Textmesh so it reduces graphical errors.
How to Create Custom Font in TextMesh Pro???
- If you want to use custom font then you have to create font asset for TextMesh Pro Text.
- Download free font from website which offer free fonts.
- Click here to Download Fonts
- Create a new folder with name as “Fonts” and add new font file here.
- Open the Font Asset Creator Menu from window.
Font Asset Creator
- Here you can add and create new font assets with various settings.
- Source Font File: assign a font that you want to create as an asset.
- Sampling Point Size determines at what point size the font will be created. You can either manually select the size of the font or use the Auto Sizing mode which will find the largest possible font size to fit in the given Atlas Resolution. It is recommended to use Auto Sizing.
- Font Padding determines how much space in pixel units between each character. For an Atlas Resolution of 512 X 512, a value of 5 for padding is perfect.
- Atlas Resolution determines the size of the Font Atlas. For most fonts which include the full ASCII character set, a size of 512 X 512 works usually well for Signed Distance Field Render Mode.
- Character Set determines what characters will be included in the font atlas.
- Click on save button.
- Select file path to Asset>TextMesh Pro> Fonts
- Now Select a Text object and assign a new Font in Font Asset Property
Now change few property for perfect text as below.
Final Output
How to create new material for Text Mesh Pro Text??
create new material in the Materials folder with the name “Text Glow Material”.
In-Text Glow Material,
Change shader
Open debug setting part & assign font atlas file which you created in Font Asset Creator.
How to create Glow Text Effect in Unity
- Create a new scene with name as “Glow Text”.
- Create another material for the skybox.
- Duplicate current skybox material and create another material with the name “Skybox_black“.
- Assign this skybox material in the current lighting setting.
- Add new TextMesh Pro Text in Hierarchy Window.
- Rename this text as “TextGlowEffect“.
- Change properties of the Rect transform of “TextGlowEffect” text.
- Change properties of TextMesh Pro Component of “TextGlowEffect” text.
- Change properties of the material of the “TextGlowEffect” text.
Final Output
How to create an Outline effect in TextMesh Pro
- Create a new scene with name as “Outline Text“.
- Add a new TextMesh Pro text object with name as “TextOutlineEffect” in the Hierarchy Window.
- Create a new skybox for this “Outline Text” scene.
- Create a new material for text for the “TextOutlineEffect” text.
- Go to the materials folder, Duplicate the “Text Glow Material”.
- Reset value of duplicated material and rename it as “Text Outline Material”
Assign this newly created material in the TextMesh Pro Component.
Change properties of the TextMesh Pro component of the “TextOutlineEffect” text as below.
- Now change properties of shader values in material for Outline Effect.
Final Output
How to create a Shadow effect in TextMesh Pro
- Create a new scene with name as “Shadow Text“.
- Add a new TextMesh Pro text object with name as “TextShadowEffect” in the Hierarchy Window.
- Assign white skybox material to the scene.
- Create a new material for text for the “TextShadowEffect” text.
- Go to the materials folder, Duplicate the “Text Glow Material”.
- Reset value of duplicated material and rename it as “Text Shadow Material”
- Assign this newly created material in the TextMesh Pro component.
- Change properties of the TextMesh Pro component of TextShadowEffect” text as below.
Now change properties of shader values in material for Shadow Effect.
Final Output
How to apply 3D text effect in unity
- Create a new scene with a name as “3d Text”.
- Add a new TextMesh Pro text object with name as “TextOutlineEffect” in the Hierarchy Window.
- Assign a black skybox in this scene.
- Create a new material for text for the “Text3DEffect” text.
- Go to the materials folder, Duplicate the “Text Glow Material”.
- Reset value of duplicated material and rename it as “Text 3D Material”
- Assign this new created material in TextMesh Pro Component.
- Change properties of the TextMesh Pro component of the “Text3DEffect” text as below.
- Now change properties of shader values in material for 3D Effect.
Final Output
Summary
In this Article, we learn about TextMesh Pro with all its properties in details.