How do I add EventTriggers to Multiple instantiated prefabs from a list? - instantiation

I have a prefab which I am spawning a dynamic amount of.
I want to attach an event trigger to each one of them, on pointerclick, to call a method accepting an int as parameter.
I have the following code which partly works, however the event added to each prefab uses the same parameter, even though they are given as beign different.
foreach (EasterEgg EE in AllEasterEggs.List)
{
Transform x = Instantiate(EasterEggPrefab);
...
EventTrigger.Entry Entry = new EventTrigger.Entry();
Entry.eventID = EventTriggerType.PointerClick;
Entry.callback.AddListener((eventData) => { EasterEggClicked(EE.ID); });
x.GetChild(1).GetComponent<EventTrigger>().triggers.Add(Entry);
}
EE.Id on the first item will be 0, then it will be 1, then 2 etc. I have debugged to ensure that when it is adding the listener that EE.Id is the correct number, and this is true. The trigger is being added correctly.
However when I trigger the trigger (how to say that?), the parameter beign passed is always the parameter of the last item in that list. For example, if AllEasterEggs.List contains 5 elements, all elements will have a trigger on pointer click calling EasterEggClicked(4), whereas they should be EasterEggClicked(0) thru EasterEggClicked(4).

As a request, this is the answer:
Instead of passing EE object to anonimous delegate, just store value of EE.ID before and pass this:
foreach (EasterEgg EE in AllEasterEggs.List)
{
Transform x = Instantiate(EasterEggPrefab);
...
EventTrigger.Entry Entry = new EventTrigger.Entry();
Entry.eventID = EventTriggerType.PointerClick;
int ID = EE.ID;
Entry.callback.AddListener((eventData) => { EasterEggClicked(ID); });
x.GetChild(1).GetComponent<EventTrigger>().triggers.Add(Entry);
}

Related

Is there an Operation to block onComplete?

I am trying to learn reactive programming, so forgive me if I ask a silly question. I'm also open to advice on changing my design.
I am working in scala-swing to display the results of a simulator. With one setting, a chart is displayed as a histogram; with the other setting the chart is displayed as the cumulative sum. (I'm probably using the wrong word; in the first setting you might have bin1=2, bin2=5, bin3=3; in the second setting the first height is 2, the second is 2 + 5, the third is 2 + 5 + 3, etc.). The simulator can be slow, so I originally used a Future to compute it, and the set the data into the chart. I decided to try a reactive approach, so my requirements are: 1. I don't want to recreate the data when I change the display mode, and 2. I want to set the Observable once for the chart and have the chart listen to the same Observable permanently.
I got this to work when I started the chain with a PublishSubject and the Future set the data into the start of the chain. When the display mode changed, I created a new PublishSubject().map(newRenderingLogic).subscribe(theChartsObservable). I am now trying to do what looks like the "right way," but it's not working correctly. I've tried to simplify what I have done:
val textObservable: Subject[String] = PublishSubject()
textObservable.subscribe(text => {
println(s"Text: ${text}")
})
var textSubscription: Option[Subscription] = None
val start = Observable.from(Future {
"Base text"
}).cache
var i = 0
val button = new Button() {
text = "Click"
reactions += {
case event => {
i += 1
if (textSubscription.isDefined) {
textSubscription.get.unsubscribe()
}
textSubscription = Some(start.map(((j: Int) => { (base: String) => s"${base} ${j}" })(i)).subscribe(textObservable))
}
}
}
On start, an Observable is created and logic to print some text is added to it. Then, an Observable with the generated data is created and a cache is added so that the result is replayed if the next subscription comes in after its results are generated. Then, a button is created. Then on button clicks a middle observable is chained with unique logic (it's a function that creates a function to append the value of i into the string, run with the current value of i; I tried to make something that couldn't just be reused) that is supposed to change with each click. Then the first Observable is subscribed to it so that the results of the whole chain end up being printed.
In theory, the cache operation takes care of not regenerating the data, and this works once, but onComplete is called on textObservable and then it can't be used again. It works if I subscribe it like this:
textSubscription = Some(start.map(((j: Int) => { (base: String) => s"${base} ${j}" })(i)).subscribe(text => textObservable.onNext(text)))
because the call to onComplete is intercepted, but this looks wrong and I wanted to know if there was a more typical way to do this, or architect it. It makes me think that I don't understand how this is supposed to be done if there isn't an out-of-the-box operation to do this.
Thank you.
I'm not 100% sure if I got the essence of your question right, but: if you have an Observable that may complete and you want to turn it into an Observable that never completes, you can just concatenate it with Observable.never.
For example:
// will complete after emitting those three elements:
val completes = Observable.from(List(1, 2, 3))
// will emit those three elements, but will never complete:
val wontComplete = completes ++ Observable.never

ag-Grid set filter and sort model without triggering event

I am updating sort & filter models via api:
this.gridApi.setFilterModel(filterModels);
this.gridApi.setSortModel(sortModels);
The problem with this is I have a server request bound to the change even of both sort & filter so when user changes then the data is updated. This means when I change model on code like restoring a state or resetting the filters it causes multiple requests.
Is there a way to update the filter/sort model without triggering the event?
I see there is a ColumnEventType parameter but couldn't see how it works. Can I specify some variable that I can look for inside my event handlers to get them to ignore calls that are not generated from user?
I am trying to manage URL state so when url query params change my code sets the models in the grids but this ends up causing the page to reload multiple times because the onFilter and onSort events get called when the model is set and there is no way I can conceive to prevent this.
At the time, you are going to have to manage this yourself, ie, just before you call the setModel, somehow flag this in a shared part of your app (maybe a global variable)
Then when you react to these events, check the estate of this, to guess where it came from.
Note that at the moment, we have added source to the column events, but they are not yet for the model events, we are planning to add them though, but we have no ETA
Hope this helps
I had to solve similar issue. I found solution which working for my kind of situation. Maybe this help someone.
for (let j = 0; j < orders.length; j++) {
const sortModelEntry = orders[j];
if (typeof sortModelEntry.property === 'string') {
const column: Column = this.gridColumnApi.getColumn(sortModelEntry.property);
if (column && ! column.getColDef().suppressSorting) {
column.setSort(sortModelEntry.direction.toLowerCase());
column.setSortedAt(j);
}
}
this.gridApi.refreshHeader();
Where orders is array of key-value object where key is name of column and value is sorting directive (asc/desc).
Set filter without refresh was complicated
for (let j = 0; j < filters.length; j++) {
const filterModelEntry = filters[j];
if (typeof filterModelEntry.property === 'string') {
const column: Column = this.gridColumnApi.getColumn(filterModelEntry.property);
if (column && ! column.getColDef().suppressFilter) {
const filter: any = this.gridApi.getFilterApi(filterModelEntry.property);
filter['filter'] = filterModelEntry.command;
filter['defaultFilter'] = filterModelEntry.command;
filter['eTypeSelector'].value = filterModelEntry.command;
filter['filterValue'] = filterModelEntry.value;
filter['filterText'] = filterModelEntry.value;
filter['eFilterTextField'].value = filterModelEntry.value;
column.setFilterActive(true);
}
}
}
Attributes in filter:
property - name of column
command - filter action (contains, equals, ...)
value - value used in filter
For anyone else looking for a solution to this issue in Nov 2020, tapping into onFilterModified() might help. This gets called before onFilterChanged() so setting a value here (eg. hasUserManuallyChangedTheFilters = false, etc.) and checking the same in the filter changed event is a possible workaround. Although, I haven't found anything similar for onSortChanged() event, one that gets called before the sorting is applied to the grid.
I am not sure any clean way to achieve this but I noticed that FilterChangedEvent has "afterFloatingFilter = false" only if filterModel was updated from ui.
my workaround is as below
onFilterChanged = event:FilterChangedEvent) => {
if(event.afterFloatingFilter === undefined) return;
console.log("SaveFilterModel")
}

Create an Array from list of objects in MaxScript and add them to a new layer

I'm super new to Maxscript and want to automate a process, I've been looking at some tutorials, but I'm running into a issue with selection. What I'm trying to do, is I have a list of strings (that I might have to add to) that represent objects in the max file that I want to select (if they exist in that file) and then add to a new layer.
for instance:
/* I have a big long list of objects I want to mass select, this has to be hardcoded because its a similar list that exists in a ton of max files */
rObj1 = "testObj1"
rObj2 = "sampleObj2"
""
rObj99 = "newObj90"
/*I want to then add it to an array
removeList = #(rObj***)
/* Then run through each entry in the array to make sure it exists and then add it to my selection
for i in removeList do
(
if i != undefined then select (i)
)
/*Then Add what I have selected to a new layer
newLayer = LayerManager.newLayerFromName "removed_list"
for obj in selection do newLayer.addNode obj
I keep getting an error when it comes to selection, being new to Max I'm not sure what to do.
You are trying to select string where you should be selecting (or adding to the layer) an object:
newLayer = LayerManager.newLayerFromName "removed_list"
for objName in removeList where isValidNode (getNodeByName objName) do
newLayer.addNode (getNodeByName objName)

Set object properties after setting the object

I've created a class with various properties in VB6.
The properties are
PiccoId
OrderId
UserId
StockCode
Quantity
At the top of the class I have declared 2 instances of classes I'm using.
Dim stkLine As CSOPSLine ' This is the class where the properties are declared and read
Private SOPSLines As cSLine ' This class creates the new objects and sets the property values
When the user enters the order number on a handheld barcode scanner, I'm creating an object to associate with this particular scanner like so:
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
In the next stage of the process, the user needs to enter their user ID so it can be seen which user scanned in the item.
I need to update the property of this same object, but I'm not sure how - Currently I am trying to do it within my getSOPSLine function, like this:
Dim line As New CSOPSLine
Dim bFound As Boolean
bFound = False
For Each line In SOPSLines.Items
If line.PiccoId = ID Then
line.OrderId = OrderId
line.Quantity = Qty
line.StockCode = stock
line.UserId = UserId
Set getSOPSLine = line
bFound = True
Exit For
End If
Next
If bFound = False Then
Set line = SOPSLines.Add(ID, OrderId, UserId, stock, Qty)
Set getSOPSLine = line
End If
Set line = Nothing
However, as I'm not storing sOrder at class level (Due to the fact multiple users can be using barcode scanners, the order ID can't be kept at class level as other users will just overwrite it),
I'm not sure how once I've got the next variable (In this case, userID, and the other variables after this stage) I can update the same object as I've just created.
I've tried to do something like
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
but it errors saying
object or with block variable has not been set
How can I update the properties of stkLine without constantly creating new objects?
EDIT
To clarify:
When the application receives data from the handheld barcode scanner, a select case is entered, with one case for each of the variables being entered (E.g. Order ID, user ID, stock code etc.)
The first case sets the order ID.
The code here is
Case FRAME_ORDER_SELECTION
On Error Resume Next
Dim sOrder As Long
sOrder = Picco.GetData(ID, 50)
If sOrder = 0 Then
Call Picco.Send(ID, FRAME_ORDER_SELECTION)
Exit Sub
Else
With Picco
Call .ClearForm(ID)
Call .Text(ID, LINE_1, "===== User ID =====")
Call .Text(ID, LINE_2, "")
Call .NewField(ID, 60, 5, FLD_LINE + SND_ENTER)
Call .Send(ID, FRAME_LINE_ADD)
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
End With
End If
frameid = FRAME_LINE_ADD
m_iLastFrameId = FRAME_ORDER_SELECTION
On Error GoTo Picco_DataArrived_Err
This is where the object is created.
The next case is after the user enters their user ID into the scanner.
Case FRAME_LINE_ADD
On Error Resume Next
Dim pUser As String
pUser = ""
pUser = Picco.GetData(ID, 60)
If pUser = "" Then
Exit Sub
End If
On Error GoTo Picco_DataArrived_Err
With Picco
Call .ClearForm(ID)
Call .Text(ID, LINE_1, "===== Add Line =====")
Call .Text(ID, LINE_2, "")
Call .Text(ID, LINE_7, "Scan or type code")
Call .NewField(ID, FIELD_POS, 18, FLD_LINE + FLD_READER + SND_ENTER)
Call .Send(ID, FRAME_LINE_QTY)
End With
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
frameid = FRAME_LINE_QTY
m_iLastFrameId = FRAME_LINE_ADD
Then there will be 2 or 3 more cases when populating the rest of the required values.
What I need to do, is in the second case (And all other following cases) update the properties of the object created in the first case.
I'm using the getSOPSLine function as this gets the object with the matching barcode scanner ID (As multiple users may be accessing different orders, they need to be kept separate in this way), but I'm not sure how to update the object where the scanner ID matches.
When you call getSOPSLine in each Case, enter some temporary values for the variables that you're not setting.
Example;
In the UserID case: stkLine = getSOPSLine(ID, 0, pUser, "", 0)
Then, in the getSOPSLine() function, change it so that instead of setting the values automatically, it instead only updates them if they don't equal 0, or "", or whichever temporary variables you use.
That way you're updating the same object, but aren't storing data that may get overwritten.
I'm not sure what you're confused about; I think that you must have some misunderstanding of what objects, variables, and properties are that is preventing you from asking this in a way that I understand. I'm not sure how your code lines up with your questions. But I'll give this a shot:
Private SOPSLines As cSLine
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
This declares a class-level variable, that can hold a cSLine object. That seems reasonable. Then you create a new instance of cSLine to put in that variable. But I don't know why, because you then point the variable to a different instance entirely, which is the instance returned from your getSOPSLine function. That middle line doesn't seem to be doing anything, and I'm not sure what you're trying to do with it.
I've tried to do something like
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
but it errors saying
object or with block variable has not been set
Well, then it sounds like stkLine isn't set to an object. I don't see any code that's trying to set stkLine other than that line. So when you try to get stkLine.OrderId, there isn't an object to get the OrderID property of, so it gives you an error.
I need to update the property of this same object, but I'm not sure how
Well, if there's an object you care about, you probably have it in a variable somewhere. You use variable.property = value syntax to assign value to the property of the object currently stored in variable.
But again, I'm not sure where your confusion is, since you're clearly assigning properties of objects in your code already.
If you're not understanding how objects work in VB, I'd recommend reading through the Working with Objects chapter of the documentation.
And if your confusion lies elsewhere, perhaps you could put together a more specific question about what you're trying to do?

What approach should be made to successfully use a specific variable?

I have a function were in I need to update multiple dropdown lists.
Since I want to remove manual interventions, I want the test to automatically decide which data to be used.
I have 2 sets of array/variable on my main tests.
arrDefinition1 = ['Section;Sec1', 'Domain;test1', 'Process layer;test1', 'Skill;test1'];
arrDefinition2 = ['Section;Sec2', 'Domain;test2', 'Process layer;test2', 'Skill;test2'];
If the current value of the dropdown list is "Sec1" then arrDefinition2 will be used and vise-versa.
But due to promises, my IF condition was executed first before the IT and the variable that contains the value of getText contains "undefined", which means arrDefinition2 will always be used.
it('should click the Edit icon of the first row of Activity table', function() {
waitForElement(5, elmFirstRow, true);
editFirstRow.click();
waitForElement(5, element(by.id('section')), true);
element(by.id('section')).getText().then(function (tmpText) {
tempObject.strSection = tmpText;
});
});
if (tempObject.strSection == 'Sec1') {
console.log('first');
fillUpForm(0, tempObject.arrDefinition2, 'UpdateMDef');
} else {
console.log('second');
fillUpForm(0, tempObject.arrDefinition1, 'UpdateMDef');
}
Note: The function fillUpForm consists of IT functions.
Any suggestions are very much appreciated.