Is there a way that converting a certain number of a unit into a specific one can change the value of a variable?

In a scenario I try to make an objective where if a monk converts 5 siege cannons the siege cannon is enabled to create, but no matter the converted cannon is destroyed, I want the variable to be kept and the value of the variable to be added as cannons are converted. I have tried the “own objects” condition and the “count units per variable” effect but it changes the variable if the siege cannon is destroyed. I can use the “attributes” condition with “converted objects” but it takes all the converted objects not just the cannons, is there a way to do this that I am looking for?

I don’t know about triggers, but you can do this with xs. You would keep a list of IDs of already converted cannons, dead or alive, and regularly check if you currently own one that’s not yet on the list. If yes, add it to the list. And if the list is long enough, enable training them.

It should be a short script, let me know if you want help.

Hm, yes it’s possible.

Just make an area on your battlefield where you can donate guns for study, and a double objective method. Either when the player owns like 10 guns with the “object in area” detecting 10 guns for the player on the entire map, or “study 5 guns” by donating 5 guns in a specific area of the map where you just make those units “not selectable” and “not attackable” with triggers so they become unavailable objects until the goal is reached.

To set the entire map area you just have to put the selection on the bottom south corner, and then edit the number values so it covers from like 0,0 to 239,239 on a map size of 240.

Hello.
if I would be interested in an XS script to do the condition I am looking to do. I would appreciate it if you would help me do it

I wrote a short script, assuming you only need this for one player, and that you already have a trigger effect to enable the cannons. But it could be extended if needed.

Inside, there is a variable cannonsCount , a function cannonsCondition to check if it reached the threshold, and a rule cannonsUpdateCount that runs every game tick until the threshold is reached.

Here’s what you need to do:

  • Include the script in your scenario. If you’re not familiar with xs, a simple way is to make an inactive trigger with a script call effect and paste the script contents into it. Or read here For Beginners - AoE2DE UGC Guide about including it as a separate file.

  • In your trigger for enabling the cannons, use a script call condition with the message cannonsCondition.

You can edit the threshold on op of the script. And in the rule, I left a line that messages you as you convert new cannons. It might help you see if it works the way you want, but you can delete it later, it’s the one with xsChatData(...);

Let me know how it goes!

cannons.txt (1.2 KB)

Thanks for the help. I tried the script, and it works well. A chat message pops up showing me the converted cannons. But I was looking for something specific: in the editor, under triggers, you can set a condition that executes an effect when a variable has a certain value. Is there a way for that same script to also add the number of cannons counted to a variable called “cannons” (without the quotation marks)? I’ll show you some screenshots.

Ahh yes you can do that too. On top, I added
const int cannonsVariableID = 47;
where you’ll need to change the 47 to the variable you are using.

And inside the update rule, I added a line that will keep that variable updated:
xsSetTriggerVariable(cannonsVariableID, cannonsCount);

You can use the variable value condition or the script call condition to check if cannons >= 5, both will work the same way.

cannons.txt (1.2 KB)

Works to 1000 wonders

Thank you very much
How much do I owe you?

1 Like

If you don’t mind, I would like to expand this question a bit - how can I do similar thing with any kind of unit, not just canons?
And were did you get the const int cObjBombardCannon = 36; from?
I looked into the guide you linked and seeing there is extension for VS Code now I decided to play around. I looked in few different places by I don’t know were did you get the 36 for the cannon from.
I’ve seen example for xsGetPlayerUnitIds here .xs scripting in Age of Empires II: Definitive Edition | Forgotten Empires and it writes 4 for archers and 904 for for villagers. I’ve found the 904 in the constants list Constants - AoE2DE UGC Guide but I don’t know were to find the 4 for the archer or 36 for the cannon.

I wanted something simpler and more flexible to tell me when a unit is acquired or lost. Since there are no any kind of events you can track in the script I though about having arrays of new and removed units that is updated on every turn. I tried to write this but I failed miserably. My idea was to get all units with the xsGetPlayerUnitIds() on every frame and compare it with previous in order to tell which units are new and which were removed. Looking at the units IDs I though that maybe it would be feasible to do it efficiently by having global array of all units states were each state is indexed by unit’s id so I don’t need to compare every unit with every other…

The idea was simple but it works only sometimes and I can’t figure out why. So basically I initialize allUnits = xsArrayCreateInt(0, -1);

currentUnits = xsGetPlayerUnitIds(playerId, 36, currentUnits);

for (i = 0; < xsArrayGetSize(currentUnits)) {
	int u = xsArrayGetInt(currentUnits, i);
	if(u < 0){
		xsChatData(fstr("invalid id: {u}"));
		continue;
	}
	int sizeNeeded = u + 1;
	if (xsArrayGetSize(allUnits) < sizeNeeded){
		xsChatData(fstr("Resizing all units to {sizeNeeded}"));
		xsArrayResizeInt(allUnits, sizeNeeded);
	}

	int eu = xsArrayGetInt(allUnits, u);
	if (eu < 0){ //does not exist yet
		xsChatData("new unit!");
		xsArraySetInt(allUnits, u, changeCheckTurn);
		if(xsArrayGetSize(newUnits) < newUnitsCount+1)
			xsArrayResizeInt(newUnits, xsArrayGetSize(newUnits)*2);
		xsArraySetInt(newUnits, newUnitsCount, u);
		newUnitsCount++;
	} else { //alive
		if(lastCount == 0) {
			xsChatData(fstr("[{u}]alive! {eu}"));
			lastCount++;
		}
		xsArraySetInt(allUnits, u, changeCheckTurn);
	}
}

But sometimes I get random numbers of eu under “[170]alive! 934184” on the first read where array values suppose to be initialize to -1.

Here is a full (cleaned up) script file if you can take a look.

cleaned.txt (4.0 KB)

And here is the working/sandbox version which I’m actually running, in case I messed something up with the cleanup

test.txt (6.1 KB)

Ok, I figured out what was the problem and solved this and other problems. I assumed the array remembers it’s default value from it’s initialization and it’s reused by the xsArrayResizeInt() since the function doesn’t have a parameter for default various. So I fixed that by writing my own resize function.
I still don’t know how to get all units though and the only thing I came up with is this:

int getAllUnitsIDs(int playerId = 1, int array = -1){
    static int units = -1;
    for(i = 900; < 965) {
        units = xsGetPlayerUnitIds(playerId, i, units);
        int cc = xsArrayGetSize(units);//current count
        if (cc == 0) continue;
        int ts = xsArrayGetSize(array);
        xsArrayResizeInt(array, ts + cc);
        for(j = 0; < xsArrayGetSize(units)) {
            xsArraySetInt(array, ts + j, xsArrayGetInt(units, j));
        }
    }
    return (array);
}

But it doesn’t seem efficient, to do it on every turn.

And I also have new weird problems. Can you confirm I can actually shrink array with xsArrayResizeInt(newUnits, newUnitsCount); while keeping the initial items intact? It’s very hard to debug this having only chat for trace and such high framerate…
What I’m guessing is I can reuse bigger array, change only initial items to relevant values and when I set the array to smaller size it will shrink from the end right?
For example I have 6 length array I want to reuse and add have only 3 length array at the end ie.

//newUnits -> [R, R, R, _, _, _]
xsArrayResizeInt(newUnits, 3)
//newUnits -> [R, R, R]

This is how it currently looks like:
test.txt (7.6 KB)

Ok, I actually messed up this method I’ve just posted and just fixed it, but I’m still not fan of how it looks. Is it really the only way to do it?

int getAllUnitsIDs(int playerId = 1, int array = -1){
    static int units = -1; int us = 0; int p = 0; //used size, position
    for(i = 900; < 965) {
        units = xsGetPlayerUnitIds(playerId, i, units);
        int cc = xsArrayGetSize(units);//current count
        if (cc == 0) continue;
        us = us + cc;
        if (us > xsArrayGetSize(array)) xsArrayResizeInt(array, us);
        for (j = 0; < xsArrayGetSize(units)) {
            xsArraySetInt(array, p, xsArrayGetInt(units, j));
            p++;
        }
    }
    return (array);
}

So all the things look to work fine now, but now I have problem that when the unit is killed, besides the kill notification I got notification of new unit bein spawned, which apparently is a unit of a dead body…
Also I don’t understand why I get two Town Center units if I only have one. Other things look ok for now.

test.txt (8.3 KB)

Hi, yes you need to initialize resized arrays manually.

Shrinking arrays should work fine as far as I know. For easier debugging, you can set rules to run less frequently, e.g. rule myRule minInterval 5 {...} to run every 5 seconds. I just used the default which is highFrequency (=every tick).

To get “all” units for a player, you can use xsGetPlayerUnitIds(playerId, -1, ...). (It might not be literally all, like probably not some obscure gaia objects.)

You can find object IDs and other stats for example using AGE3, it comes with the game files:.../AoE2DE/Tools_Builds/AdvancedGenieEditor3.exe

In general I think your approach should work, although I would worry about allUnits being very large. Just trees can be tens of thousands of elements, and it will keep growing as new units get created. So if you loop over it, I’m not sure it will actually be much faster than pairwise comparisons for specific types of units.

If you need this to run fast for lots of units, there might be a way by tracking the highest existing unit ID or paying attention to the order in arrays returned by xsGetPlayerUnitIds. Newly created units should get progressively higher IDs, and both new and converted/transformed units seem to go to the end of the array.

1 Like

Also there could be another array like “acquired”, with all units IDs that were detected as new. Those would be subject to filtering so there will be no trees and other irrelevant objects and instead of looping through all items of allUnits the units remove detection would loop trough only indexes in this acquired array…

I just tried it out of curiosity, and you can detect new units very efficiently by looping over new IDs. Note that this yields all the newly created units, regardless of type/player (even dead units, flares, etc), and it doesn’t tell you about converted units.

const int cObjInvisibleObjectA = 1291;

void processUnit (int u = -1) {
    string name = xsGetUnitName(u);
    xsChatData(fstr("New unit: {u} '{name}'"));
}

int _probeUid () {
    int u = xsCreateUnit(cObjInvisibleObjectA, 0, xsVectorSet(0.5, 0.5, 0.0), false, false, false);
    xsRemoveUnit(u);
    return (u);
}

rule findNewUnits
    highFrequency /* necessary to prevent gaps in ID sequence */
{
    static int next = -1;
    if (next == -1) {
        next = _probeUid();
        for (u = 0; < next) processUnit(u);
    }
    while (xsDoesUnitExist(next)) {
        processUnit(next);
        next++;
    }
}

It keeps checking if there exists a unit with the next ID, and if yes, processes it and increments next.

In the very beginning, there can be gaps in the ID sequence because of units removed before the rule first runs. Gaps like that would break the loop, but to work around that, I make a “probe” unit to see what ID it gets, and loop all the way to that value.

Later, I don’t think there should be any more gaps, but I’m not 100% sure. If it turns out to be an issue, you can just make a new probe every time. It’s a tiny overhead, but since it handles gaps it doesn’t have to run at highFrequency.

rule findNewUnitsSafer
    minInterval 1 /* or highFrequency */
{
    static int start = 0;
    int end = _probeUid();
    for (u = start; <= end) processUnit(u); /* use < to skip the probe unit */
    start = end + 1;
}

This is very good idea. Certainly much better then querying all existing units on very turn. To have a complete tracking that is reusable and reliable there still have to be a full frequency unit examiner to tell when a unit was acquired or lost. For example a sheep could possibly switch sides few times in one second so we would have to check it’s owner on every turn to make sure we truly know what happened but there will be a limited number of interactive units to track i.e. max 1600+anmials for standard game settings. Not needing to additionally query all those units and joining over 50 arrays for every player each turn is a huge optimization…

Hym… after second though, the buildings could be also converted so theoretically we can fit 57 600 houses on the largest map… -1 to give space for a monk :smiley: