Do I have to create a reference for each text I have in a panel, if I want to access them to modify? - unity3d

I have a panel with 8 text field, 4 are used as descriptive field (what a label would do, basically), while the other 4 are modified with values.
I am creating a GameObject variable for every element that I have in the panel, using find to find the specific text element. I can leverage on the fact that each text object has only one text object attached to it, so I can address to it directly with GetComponent
panel_info = GameObject.Find("infopanel");
textfield1 = GameObject.Find("text_name");
textfield2 = GameObject.Find("text_age");
textfield3 = GameObject.Find("text_role");
textfield4 = GameObject.Find("text_field");
textfield1.GetComponent<Text>().text = "joe";
textfield2.GetComponent<Text>().text = "22";
textfield3.GetComponent<Text>().text = "striker";
textfield4.GetComponent<Text>().text = "attack";
While this works, I can't foresee myself creating 20-30 objects if a panel has more info to display.
Since I have the reference to the object Panel, is there a way to address directly the text field which is a child of the panel, using the text field name for example?
So if a panel has 4 text field, I can modify each of it addressing directly by name, and then using GetComponent<Text>().textto change the value.

You MUST NOT call GetComponent<Text>() each time you want to access/modify text.
This is an extremely basic fact about Unity.
It is immediately mentioned in the relevant manual entries.
Since you have 8 textbox and I don't know how long you update each one. It would be good if you cache all of them in the beginning of the game then use them later on without GetComponent<Text>(). This will improve performance a lot and make your frame-rate happy.
Array looks good for something like this. And you need to comment each one too.
public Text[] textBoxArray;
On the editor, Expand the "Text Box Array" and change the array Size to 8.
Now drag each GameObject with the text to the arrays in order. If you do it in order, you can easily remember their names and be able to access them in order.
For example, if the first text gameobecjt you dragged to the array is called text_name, the access it, you use textBoxArray[0]. The second text which is text_age can be accessed with textBoxArray[1]. .....
To make it easier for you later on, you should have multiple line comment that describes which array points to what.You do this so that when you return to modify your code months after, you won't have to look around in the Editor to find what points to what. For example:
/*
textBoxArray[0] = text_name
textBoxArray[1] = text_age
textBoxArray[2] = text_role
textBoxArray[3] = text_field
*/
No performance lost and that decreases the amount of code in your game.
Initializing the arrays by code instead of the Editor
Assuming you want to initialize the arrays by code instead of the Editor. You can do it in the start function like below.
public Text[] textBoxArray;
void Start()
{
//Create arrays of 8
textBoxArray = new Text[8]; //8 texts
//Cache all the Text GameObjects
textBoxArray[0] = GameObject.Find("/infopanel/text_name").GetComponent<Text>();
textBoxArray[1] = GameObject.Find("/infopanel/text_age").GetComponent<Text>();
textBoxArray[2] = GameObject.Find("/infopanel/text_role").GetComponent<Text>();
textBoxArray[3] = GameObject.Find("/infopanel/text_field").GetComponent<Text>();
}
You should notice that GameObject.Find() starts with "/" and that increases performance too as it will only search for Texts under "infopanel" instead of searching in the whole scene.

Assuming that your hierarchy is setup that all your TextMeshes are children of the panel, you could use the Transform.Find method to get each child, then it's TextMesh, and assign a value.
So, for example, if you wanted to assign the value "Joe" to the TextMesh attached to "text_name", which in turn is a child of "infopanel", you could do the following
panel_info = GameObject.Find("infopanel");
panel_info.transform.Find("text_name").GetComponent<TextMesh>().text = "Joe";

Related

How do I arrange a list of buttons into rows of 4

I am trying to display the same game object in a table form of 4 columns and 2 rows so it would look like this:
GO GO GO GO
GO GO GO GO
G0 - gameObject
My gameObject is a button that can be pressed and has a text element on it to display the name of the profile on the button.
I have a List of strings of the names that i need to display on these GO buttons in the table form but i am struggling to position them correctly.
At the moment i have gotten to the point where i can Instantiate them so they all appear on the screen when the game is running, now i just need some advice on how i can position them properly in the format mentioned above.
How do i do this?
This is my code that i used to get the names and add them to the List:
private void GetProfiles()
{
List<string> profileNamesList = new List<string>();
if (Directory.Exists(filePath))
{
string[] files = Directory.GetFiles(filePath);
profileTileTemplate.SetActive(true);
foreach (var file in files)
{
string name;
name = file;
int index = name.IndexOf(filePath + "/", System.StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
int pathIndexEnd = index + filePath.Length + 1;
int stringLength = name.Length - pathIndexEnd - 5;
name = name.Substring(pathIndexEnd, stringLength);
}
profileNamesList.Add(name);
}
}
DisplayProfiles(profileNamesList);
}
private void DisplayProfiles(List<string> names)
{
}
I have tried using a for loop with in another for loop but i just end up instantiating multiple of the same game object.
This is what i get now:
And this is what i want it to look like:
This is kind of two questions, and I just realized that Unity has a built in component that will do this automatically, so I'll leave the three answers below.
How do I arrange UI gameobjects in rows?
Since it seems like you want to do this for UI elements there's actually a very easy solution. Add an empty GameObject as a child of your Canvas and add a Vertical LayoutGroup component. Add two children to that with horizontal layoutgroups. Add four placeholder prefabs of your gameobject to each horizontal layout group. Arrange them and configure the settings to get them looking the way you want (and make note of what happens if you add fewer than four items!)
Once you have it all set up, delete the placeholders. Then you can add your gameobjects to the horizontal group using Instantiate(Object original, Transform parent) (link) to parent them to the layout group, which will keep them arranged neatly. You can keep a list of those groups and each time you add four, switch to the next parent.
A neater way that seems to fit your use case (assuming there can potentially be more than 8 profiles) is to make a Scroll View that holds horizontal layout groups, which will each be a row of entries. That way instead of tracking which parent you want to add gameobjects to, you can just instantiate a new row every time you pass four entries.
If you're sure there will only ever be eight or fewer, the easiest thing to do would just be arrange eight blank buttons in the UI however you want them to appear. Then keep a list of the eight buttons and edit the text/image on them, no instantiation or looping necessary.
How do I split up a list of gameobjects into rows?
The actual code to process the list is below. This is just an example and there are plenty of different ways to do it, but I thought this demonstrated the logic clearly without depending on what UI elements you choose. As a rules of thumb, make sure to figure out the layout elements you like in Unity first using placeholders (like scroll view etc) and then figure out the code to fill them in. In other words, instantiating and laying out UI elements at runtime is a great way to give yourself a headache so it's best to only do it when you need to.
List<string> profileNamesList = new List<string>();
public int entriesPerRow; //only public so you can edit in the inspector. Otherwise, just use the number per row in your prefab.
public GameObject profileRowPrefab;
public GameObject scrollViewLayout;
private void DisplayProfiles(List<string> names)
{
int i = 0;
while( i < names.Count ) //"while the list has more names"
{
//create a new row as a child of the scroll view content area
//and save a reference for later
GameObject go = Instantiate(profileRowPrefab, scrollViewLayout);
for(j = 0; j < entriesPerRow; j++) //"add this many names"
{
if(i < names.Count)
{
//instantiate a button, or edit one in the row prefab, etc.
//depending on how you're doing it, this is where you'd use the go variable above
YourProfileButtonCreationMethod(names[i]);
i++;
}
else
{
//we've finished the list, so we're done
//you can add empty placeholders here if they aren't in the prefab
break;
}
}
}
}
YourProfileButtonCreationMethod will depend completely on how you want to implement the UI.
I wish I had thought of this an hour ago, but I've never used it myself. Unity has a built in layout feature that will do this for you (minus the scrolling, but you may be able to nest this in a scroll view).
How do I arrange UI elements in a grid?
Instead of making your own grid with horizontal and vertical layout groups, you can use the Grid Layout Group. Then just instantiate each item in the list as a button with the grid layout as their parent (see above). Here's a short video tutorial that shows what the result looks like.

Set backend title for Mask-Elements in Typo3

I have a Typo3 server. On that I created some different content elements with mask.
In this elements there are often repeating content, like texts or other stuff.
So the editors make a new element in the backend, there they can add a headline and as much text parts as they want.
Often it looks like this:
Thats good, the editor can see a "preview" of the textparts. In this example "Karriere,Partner...". This naming happens automatically.
My Problem is, some times there arent any titles. Its always "No title". As an editor its quite hard to find the right dropdown to edit some stuff, you mostly have to open all dropdowns and search for the right one.
Its look then like this:
In both elements there are some string inputs that are very good for the title.
So my question is, how is mask gonna choose the title? Its not the first string input.
And secondly, can I tell Mask that they have to choose input field XYZ as title?
Heyo
Yes, you can tell Mask which field to use as a title for inline elements (like repeating contents). When you're setting up a new Mask element, right below the "Label" field of the repeated inline element, there is a field "Field that should be used as label for inline element (starting with tx_mask_)". This will be used as the title that is displayed in the backend. In the placeholder of that field, it explicitly says that "If empty, first field is used".
So, if your inline element has a field "my_awesome_header" which you would like to use as the title in the backend, set the above to "tx_mask_my_awesome_header".
I am not certain as to why it does not display anything in your second example. It might be that either the first input field is not a string, or the first input field is a string but it is empty.
I hope this helps. Let me know if you need further clarification.
Edit: Since that question came up, it should be possible to set a static default title to the containing Mask element using mod.wizards.newContentElement.wizardItems.mask.elements.[name of the mask element].tt_content_defValues.header = My awesome static title. As I said in the comments, though: I always give my Mask elements a header field and let editors fill that in.

How to insert a non-inline picture into a word document using VB6?

I am trying to insert an image into a word document using the Microsoft word 15.0 objects library included with VB^ and the only way I've seen to insert a graphics file is through this:
oDoc.Range.InlineShapes.AddPicture ("C:\Users\name\Desktop\file.jpg")
But, I want a picture that can be positioned over the text and where I want it in the document... Is there any way to do this using VB6 Code?
Word has two different ways to manage images and other embedded objects: as InlineShapes and as Shapes. The first are treated the same as characters in the text flow; the latter have text wrap foramtting and "live" in a different layer from the text.
To insert a graphics file as a Shape:
Dim shp as Word.Shape
Set shp = oDoc.Shapes.AddPicture(FileName, LinkToFile, _
SaveWithDocument, Left, Top, Width, Height, Anchor)
The AddPicture method returns a Shape object. Often, this is useful when additional properties need to be set after the object has been inserted. For example in order to specify the text wrap formatting. If no Shape object is required a Shape can be inserted without assigning to an object. In this case, leave out the parentheses:
oDoc.Shapes.AddPicture FileName, LinkToFile, _
SaveWithDocument, Left, Top, Width, Height, Anchor
While only the FileName argument is required, the last argument - Anchor - is very important if you want to control where the image is positioned when it's inserted.
It's also possible to insert as an InlineShape then use ConvertToShape in order to have a Shape object to which text wrap formatting can be applied.
Every Shape must be associated with a Range in the document. Unless otherwise specified, this will be the first character of the paragraph wherein the current selection is. I strongly recommend passing a Range to the Shapes.AddPicture method in the Anchor argument for this reason.
Note that once a Shape has been inserted there's no direct way to change the anchor position. It can be done using cut & paste. Another possibility is to use the ConvertToInlineShape method so that you can work with the Range to move the graphic, then ConvertToShape to turn it back into a Shape, but in this case a number of positioning and wrap properties may need to be reset. Here an example of using the "convert" methods:
Sub MoveShapeToOtherRange()
Dim oDoc As Word.Document
Dim shp As Word.Shape
Dim ils As Word.InlineShape
Dim rngEnd As Word.Range, rngStart As Word.Range
Set oDoc = ActiveDocument
Set rngStart = oDoc.content
rngStart.Collapse wdCollapseStart 'start of document
Set rngEnd = Selection.Range
Set shp = oDoc.shapes.AddPicture(fileName:="C:\Test\icons\Addin_Icon16x16.png", _
Top:=0, Left:=10, anchor:=rngStart)
Set ils = shp.ConvertToInlineShape
Set rngStart = ils.Range
rngEnd.FormattedText = rngStart.FormattedText
rngStart.Delete
Set ils = oDoc.InlineShapes(1)
Set shp = ils.ConvertToShape
End Sub
By default, a Shape will insert with MoveWithText activated. That means the position on the page is not set, editing will affect the vertical position. If you want the Shape to always be centered on the page, for example, set this to false. Note, however, that if the anchor point moves to a different page, the Shape will also move to that page.
On occasion, the Left and Top arguments don't "take" when adding a Shape - you may need to set these again as properties after adding it.
Ok, What I ended up doing that worked was this:
Dim a As Object
On Error Resume Next
a = oDoc.Shapes.AddPicture("C:\Users\name\Desktop\file.jpg", , , 25, 25, 25, 25)
For some reason, This places the image at the position and size. When I looked at the docs for ".AddPicture" I realized it returns a Shapes object. So I just had it store it in a throw-away object. For some reason it then would respond with an error, but would end up placing on the doc anyways. So I used:
On Error Resume Next
This skips the error. After that, the picture places as expected and the rest of the doc is made as expected
Thank you for your answers

Reference Table to fill calendar form

In Access 2010, I've built a calendar Form that I want to be able to display who is off in a given month.
Each box of the calendar obviously represents a different day. I've got a table called "Separated" set up that ultimately stores the associate name and the date they are off -- one day per record.
Here's what I've done so far to try to test it on just one of the boxes (representing a day):
Private Function fillDays()
Dim rsNames As DAO.Recordset
Set rsNames = CurrentDb.OpenRecordset("SELECT * FROM Separated")
If Not rsNames.EOF Then
b0.Text = rsNames![Associate]
End If
Set rsNames = Nothing
End Function
I get the following debug note:
"Run-Time Error '2185"
"You can't reference a property or method for a control unless the control has the focus."
The debugger highlights the line with "b0.text = rsNames![Associate]
Is there some whay that I need to reference an index number from my "Separated" table?... or perhaps using a query method of some sort would be more effecient.
Assuming b0 is a textbox, the error you are getting is due to the fact that you can't use it's Text property when said textbox hasn't got the focus.
As stated in MSDN, «While the control has the focus, the Text property contains the text data currently in the control; the Value property contains the last saved data for the control. When you move the focus to another control, the control's data is updated, and the Value property is set to this new value. The Text property setting is then unavailable until the control gets the focus again» (emphasis mine).
Try using Value (help here) instead:
b0.Value = rsNames![Associate]

How to update another text box while typing in access 2007 form?

I have a few text boxes which have to be filled with numeric values from 0 to 100. Below them there is another text box which stands for a total (the sum of the values from the text boxes above). How can I update the sum text box while typing in any of the other text boxes above?
If you are happy that the sum box updates after a box is updated (enter, tab or such like is pressed), then this can be done without any code. First, you will need to set the format of the textboxes to be summed to numeric, then the control source of the sum box becomes:
=Nz([text0],0)+Nz([text2],0)+Nz([text4],0)+Nz([text6],0)+Nz([text8],0) ...
Note the use of Nz, it may be possible to eliminate this by setting the default value property of the various textboxes to be summed.
A large set of controls that need to be summed in this way is often an indication of an error in the design of the database. You would normally expect this kind of thing to be a separate recordset, which could more easily be summed.
I know this is old, but Google didn't come up with much for this topic and this thread didn't really help either. I was able to figure out a very easy way to do this, so hopefully anyone else looking for this will find this helpful.
My need was for actual text as opposed to numbers, but the same applies.
To do what the OP is asking for you'll need at least 3 textboxes. 1 is the textbox you want to have updated each time you type, 2 is the textbox you will be typing in, and 3 is a hidden textbox.
Set textbox 1 to reference the value of the hidden textbox 3 in its control source:
="something in my textbox " & [textbox3]
In the OnChange event of textbox 2 right a line that will set the value of the hidden textbox 3 to the Text property of textbox 2 that you are typing in:
Private Sub textbox2_Change()
Me.textbox3.Value = Me.textbox2.Text
End Sub
Each time the value of the hidden textbox 3 gets updated, the calculation/reference in the displayed textbox 1 will be updated. No need to save caret locations or anything else mentioned in this post.
I was able to do this in Access 2007 by using the On Lost Focus event of the text box.
Just put something like this on the On Lost focus event of each text box that you want to be added , just make sure to set the default value of each text box to 0.
Me.Totals.Value = Me.Text1.Value + Me.Text2.Value + etc..
The moment you click on the next text box or anywhere as long as it loses focus, your sum will already be on the Totals box. You may add as many text boxes as you like, just include them in the code.
This is problematic due to the asinine requirement in Access that you have to set focus to text areas before you can get their value. I would recommend you change your design so that the text field is updated in response to a button click instead of on change.
If you want to go the update-on-change route, you would attach change events to each of the addend text fields. The event handlers would need to save the caret position/selection length, update the sum in the output text field, and restore the caret position. You need to save/restore the caret position because this is lost when the focus changes.
Here's an example for two text fields (txt1 and txt2). The output field is named txtOutput.
Private Sub txt1_Change()
Dim caret_position As Variant
caret_position = Array(txt1.SelStart, txt1.SelLength)
UpdateSum
txt1.SetFocus
txt1.SelStart = caret_position(0)
txt1.SelLength = caret_position(1)
End Sub
Private Sub txt2_Change()
Dim caret_position As Variant
caret_position = Array(txt2.SelStart, txt2.SelLength)
UpdateSum
txt2.SetFocus
txt2.SelStart = caret_position(0)
txt2.SelLength = caret_position(1)
End Sub
Private Sub UpdateSum()
Dim sum As Variant
sum = CDec(0)
txt1.SetFocus
If IsNumeric(txt1.Text) Then
sum = sum + CDec(txt1.Text)
End If
txt2.SetFocus
If IsNumeric(txt2.Text) Then
sum = sum + CDec(txt2.Text)
End If
txtOutput.SetFocus
txtOutput.Text = sum
End Sub