#archived-code-advanced

1 messages ยท Page 138 of 1

undone coral
#

it is going to be something like an off by one error

#

imo, since you're so close i wouldn't change much

#

but you probably should have started with something from the literature to do this

#

meshing a grid of points

#

you would have to modify it for 2d

long ivy
undone coral
#

yeah

#

"a translation of the delphi clipper library"

#

kind of how this stuff goes

#

@frail dock bakecollider from here

mortal glen
#

i want to remove a property and value from a json string that makes my deserialization puke. How do I do this?

compact ingot
#

All this assumes you're using newtonsoft

mortal glen
#

I have spent all day to figure this out, yes I am using newtonsoft, its driving me mad

#
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TokelToken]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
compact ingot
#

seems like you are trying to deserialize an object into an array or vice versa

#

can you show the source json and target property?

mortal glen
#

its like nested

#

sure

#

in Unity

Tokels mytokeltoken = JsonConvert.DeserializeObject<Tokels>(getTokenData.downloadHandler.text);
                    Debug.Log(mytokeltoken.tokens[0]);
#

here are my classes

#
[System.Serializable]
public class Tokels
{
    public List<TokelToken> tokens;
}

[System.Serializable]
public class TokelToken
{
    public string tokenid;
    public string owner;
    public string name;
    public int supply;
    public string description;
    public TokelData data;
    public int version;
    public string IsMixed;
    public int height;
    public string ownerAddress;
    public int blocktime;
    public string blockheight;
    public int syncedHeight;

}

[System.Serializable]
public class TokelData
{
    public string raw;
    public TokelDataDecoded decoded;
}

[System.Serializable]
public class TokelDataDecoded
{
    public int id;
    public string url;
    public int royalty;
    public string arbitrary;

}
#

@compact ingot

compact ingot
#

The JSON needs Tokels to be this: ```
[System.Serializable]
public class Tokels
{
public TokelToken tokens;
}

#

And deserialize multiple Tokels, if needed, into a List<Tokels>.... but mind you that the root of the json source you linked is a dictionary/object, and not an array!

mortal glen
#

:S

fickle inlet
#

Hey I am using a new Input System and for some reason if I am going right or left I can't overweight the right and left with up or down buttons, could anyone guess what am I doing wrong?

mortal glen
#

@compact ingot I don't understand how to fix it

#

because a part of it works, except the data property

compact ingot
#

how do you know it works partially?

mortal glen
#

@compact ingot

 IEnumerator FetchAndUpdateTokens()
    {
        UnityWebRequest alltokens = UnityWebRequest.Get("https://explorer.komodoplatform.com:10000/tokel/api/tokens");
        yield return alltokens.SendWebRequest();

        if (alltokens.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(alltokens.error);
            yield return null;
        }


        Tokels tokeltokens = JsonConvert.DeserializeObject<Tokels>(alltokens.downloadHandler.text);

        for(int t = 0; t < tokeltokens.tokens.Count; t++)
        {
            if(tokeltokens.tokens[t].ownerAddress == myTokelAddress)
            {
                if(!mytokens.ContainsKey(tokeltokens.tokens[t].tokenid))
                {
                    Debug.Log("current tokenid: " + tokeltokens.tokens[t].tokenid);
                    UnityWebRequest getTokenData = UnityWebRequest.Get("https://explorer.komodoplatform.com:10000/tokel/api/tokens?cctxid=" + tokeltokens.tokens[t].tokenid);
                    yield return getTokenData.SendWebRequest();

                    Debug.Log("fetched: " + getTokenData.downloadHandler.text);

// HERE I GET THE ERROR
                    Tokels mytokeltoken = JsonConvert.DeserializeObject<Tokels>(getTokenData.downloadHandler.text);
                    Debug.Log(mytokeltoken.tokens[0]);

                }
               
            }
        }
#

@compact ingot

fetched: {"tokens":{"tokenid":"bb69cc6d5a16b459f8b3c4c83e74f619b212830adfa331c051694e3604710146","owner":"03353ec0e845ab678e8efaa3f50e96163da0eb....
compact ingot
#

first endpoint returns an array, second an object

mortal glen
#
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TokelToken]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
...
Path 'tokens.tokenid', line 1, position 21.
compact ingot
#

but you deserialize into the same type... that cant work

mortal glen
#

so I need to create a different one for the next object?

compact ingot
#

second one needs the edit i showed you

#

first one works with what you had

#

best just make the edit i suggested and deserialize the first one into a List<Tokels> variable

mortal glen
#

@compact ingot got it working thanks!

frail dock
#

ty mate this seems like something i could use

#

yeah, has to be cause it's only one thread so it should be all executing one after the other, funny thing is i tried drawing the exact shape what i did when i was going slow and that works, but if i try the exact thing fast it bugs out instantly

#

it's baffling me

frail dock
#

so i think i found the issue

#

i set it out to print the order of execution

#

it goes

#

BUTTON EXECUTE

#

START METHOD

#

START PATH

#

but for some reason button execute is called twice when i draw fast at some point

#
        if (Input.GetMouseButton(0)) {
            if (finX >= 0 && finY >= 0) {
//                print("PLACE " + wp.x +" "+ wp.y);
                if (tScript.chunks[(finX - finX % blockSize) / blockSize, (finY - finY % blockSize) / blockSize][finX % blockSize, finY % blockSize].type != 2) {
                    print("BUTTON EXECUTE");

                    tScript.chunks[(finX - finX % blockSize) / blockSize,(finY - finY % blockSize) / blockSize][finX % blockSize, finY % blockSize].type = 2;
//                    tScript.squareX = finX;
//                    tScript.squareY = finY;
                    tScript.squareX2 = finX % blockSize;
                    tScript.squareY2 = finY % blockSize;
                    tScript.chunkX = (finX - finX % blockSize) / blockSize;
                    tScript.chunkY = (finY - finY % blockSize) / blockSize;
                    tScript.squareType = 2;
                    tScript.update=true;
                }
            }
        }
#

how could this execute twice before finishing the rest of it? ๐Ÿค”

#

unless that boolean i'm flipping is messing with it somehow

untold moth
#

Also maybe use GetMouseButtonUp/Down. So that it's not executed twice if you hold it for 2 frames somehow.

pulsar summit
#

is there any directions where I can look at for having place nodes automaticly in a grid like webbing?

#

I ment like having a nodes automaticly connect when placed on the scene

frail dock
# untold moth Check the callstack of each message

hmm, so i had a bunch of booleans i was flipping to trigger each other, i put them all in a single boolean update flip and that seems to have reduced it but it still seems to trigged if i leave print outs there and execution takes too long ๐Ÿค”

frail dock
untold moth
#

No, I mean use GetMouseButtonUp instead of GetMouseButton

frail dock
untold moth
#

Aaah

#

Okay

#

Then maybe you have 2 instances of the script in the scene?

#

Add this as the second parameter of the debug.log and see if it points to a different object.

frail dock
#

no that can't be it, i only have one map object with one script attached to it

#

strange, i can't seem to trigger it now even with the prinouts

#

this is gonna haunt me knowing the possibility is there ๐Ÿฅฒ

frail dock
#

fixed! i just added a boolean to not trigger if the other code isn't finished ๐Ÿ˜„

#

it's so fast i can make my player into a rocket by placing blocks now ๐Ÿ˜„

kindred tusk
regal olive
#

Does anyone have any best practices or strategies for managing transitions between scenes, like going from a lobby to a match? Seems like there is a lot of info out there on potential ways to solve this, but I'm curious if any have been found to be lacking once a project gets to certain complexity.

foggy elk
#

Good morning all.
I have a need to search for specific fields within a class, retrieve its value (to compare it against another value).
Its a function within the AI that runs when it decides what skills to use in any given situation. The skills on each mob can vary, and so can the conditions set for those skills.
The conditions can be both int values like strength, intelligence, HP, mana but also bools like isKnockedDown or isFloating.

public class MobData : MonoBehaviour, InterfacePersonality, InterfaceDamage
    {
     public Mob thisMob = new Mob ();
    }
//THIS IS THE CLASS I NEED TO RETRIEVE A VALUE FROM
    public class Mob
        {
        public int health;
        public int walkSpeed;
        public int runSpeed;
        public int jumpForce;

        public int baseAttackValue;
        public int attackAccuracy;
        public int attackPhysicalAttackPower;
        public int attackMagicalAttackPower;
        public int atackArmorPenetration;
        public int attackCriticalChanceValue;
        public int baseDefenseValue;
        public int defenseEvasion;
        public int defensePhysicalDefenseValue;
        public int defenseMagicalDefenseValue;
        public int defenseDamageReduction;
        public int Intelligence;
        public int Bravery;
        public int Authority;
        }

======================================
  private bool CheckConditions(ScriptableMobSkill mobSkillData, StateController controller, PlayerCharacter targetCharacter)
        {
       
        foreach (var condition in mobSkillData.SelfConditions)//SEE CLASS BELOW
            {
            //HOW TO RUN THROUGH EACH TRAIT, RETRIEVE THE FIELD AND THE VALUE IN THAT FIELD THAT CORRESPONDS TO THE TRAIT?

            }
}

===================================
public class MobSkillCondition //this is used as an array in an scriptable object (Public MobSkillCondition[] SelfConditions)
    {
    public string CharacterTrait;
    public int CharacterTraitValue;
    }
hard lily
#

If I understood this correctly just add them to a list

#

Wait, that won't be necessary, I just saw the Mob class

foggy elk
#

let say one of the conditions read
CharacterTrait baseDefenseValue
CharacterTraitValue 5

In the for each loop, I need to run through and retrieve the field "baseDefenseValue" at controller.thismob and then compare the values to know if it should return true or false

#

was thinking of using controller.thismob.getfield() ? but someone warned against using reflection at runtime?

hard lily
#

I'm trying to think of an optimal way to handle this other than the obvious way of just checking trait by trait like:

...
else if(characterTrait == "baseDefenseValue")
{
    return baseDefenseValue "condition" CharacterTraitValue;
}
...
foggy elk
#

indeed, thats why I am here. Cause I want to do the same with the PlayerClass, and it contains more like 40 different values that it should be checked against xD

hard lily
#

Interesting, now I want to see the solution to this too. I'm not sure how I would do it.

foggy elk
#

think I got it

    private void CheckConditions(ScriptableMobSkill mobSkillData, StateController controller, PlayerCharacter targetCharacter)
        {
        MobData mobData = controller.gameObject.GetComponent<MobData> ();
        foreach (var condition in mobSkillData.SelfConditions)
            {
            int retrievedValue = GetPropertyValue<int> ( mobData.thisMob, condition.CharacterTrait.ToString () );
            if (retrievedValue >= condition.CharacterTraitValue)
                {
                Debug.Log ( "retrievedValue for condition  " + condition.CharacterTrait + " " + retrievedValue );
                }
           
            }
        }

    public static T GetPropertyValue<T> ( ClassData.Mob mobData, string propName )
        {
        Debug.Log ( propName );
        var type = mobData.GetType();
        Debug.Log ( type.ToString() );
        var field = type.GetField ( propName );
        Debug.Log ( field.Name );
        var valu = field.GetValue (mobData  );
        Debug.Log ( valu.ToString () );
        return (T)mobData.GetType ().GetField ( propName ).GetValue ( mobData );
        }
    }
#

all the debugs can and will be removed, that was for me understanding how it worked.

compact ingot
#

Since this is an AI thing, i'd suggest you look into the Blackboard Pattern

#

The Blackboard is just a shared collection/database that can contain multiple types (i.,e. your class fields), stored as anonymous object references together with their type such that getting a value from the Blackboard can be handled by a Strategy pattern, common, type-safe interface and casting instead of reflection... you can however use reflection for initializing/building the blackboard... or you can build GUI inspectors for all blackboard properties and consumers that handles the type safety at design-time with everything stored as plain objects in a dictionary. Or you can just ignore type safety and live with cast-exceptions.

#

If you really want to use reflection you can create value-getter delegates for each specific member when you first search for it, those are then on subsequent use much faster than using relfected member name lookup. You can combine that with the blackboard pattern.

#

Also relflection produces the ugliest code possible.,

tiny anchor
#

hi, i have these 2 scripts https://pastebin.com/2Cdm2FNx (shader), https://pastebin.com/p4bNBkRR (mesh c#) that uses a compute shader to generate a grid mesh just as a test. I want to end up doing marching cubes on the gpu but i cant figure out why my mesh loooks like this.

tiny anchor
#

i realised lol, do you know how i could fix it?

compact ingot
#

double check your understanding of the datastructure for meshes

#

also mind that vertex order in a triangle matters

#

could also be that your vertex order is different than you assume

#

i.e. x/y flipped in a for loop or something like that

#

off by 1 error

#

stuff like that

tiny anchor
#

ye ive done a lot of mesh systems before using the unity job system and c#. I understand the math but the exact same math i used in the shader is what i use in the job system. Im stuck on why it dosent work. and also im not seeing massive performance gains. that could be because im useing unity meshes instread of draw procedural but idk.

#

ill see if i can implement your advice

#

thanks

foggy elk
compact ingot
# tiny anchor thanks

do you think it could be a shared data issue, since you are building the tri indexes together with the calculations in separate threads? doesn't seem likely though.

#

could just do the pos-calc in threads and the triangles after a join... i don't see an issue in your code... maybe a rounding error between gridDetail and gridWidth?

agile yoke
#

e.g. where you write to TriangleIndices in the shader

#

You write to everything from ThreadIndex to ThreadIndex + 5

#

But the thread for one cell over in the y direction is going to write to most of the same indices (because its index is ThreadIndex + 1)

#

Missing a * 6 I guess

compact ingot
tiny anchor
compact ingot
#

๐Ÿฅฐ concurrency bugs are the best

kindred tusk
#

I think you can return ref in the new versions of C#

#

Otherwise you can do a Set/Get separately

foggy elk
kindred tusk
#

The other option is to not have fields at all

#

And instead do this:

enum FieldType {
  Attack,
  Defence,
  Speed
}

class Attributes {
  int[] fields[Enum.GetValues<FieldType>().Length];
  ref int Field(FieldType type) => ref fields[(int) type];
}
#

@foggy elk โ˜๏ธ

#

That way there's no duplication

#

You'd just always use the Field accessor instead

#

It might make defining inital stats a bit uglier though.

foggy elk
#

interessting approach. Would be some work restructuring parts of the code, but I am already using an Enum for the charactertraits.

kindred tusk
#

You can make a custom inspector for the Attributes class

#

so that it shows up in the editor like a normal struct

#

Hard to know whether this would be a help or a hindrance without knowing exactly what you're doing with it.

#

But it's an option!

foggy elk
#

this might be a newbie thing, but the class I want to retrieve values from, is a class created with updated variables when you start a new "game".
and then this class are updated each time a change is made. So everything in my code that needs information on the player variables, retrieves it from this class. A bit unsure if deleting it and making an enum out of it would be wise

#

that switch thing aint looking so stupid anymore xD

abstract geyser
#

So I have an issue with the voxel graphics where the landscapes are highly detailed and after optimization (combining cubes on the same plane etc) the resulting triangle count and vertex count is drastically reduced but still too high for oculus quest. At certain points in the game the vertex count exeedes 400k which is 4X the recommended by oculus.

The landscape is created in MagicaVoxel and imported with the MagicaVoxel Tool from the asset store that converts and optimizes the mesh. Problem is that this isn't enough. Is there a way to have highly detailed Voxel landscapes (or voxel graphics in general) where I could optimize the tris and vertex count into acceptable levels without having to let the artist reduce the detail level?

Currently landscapes come in chunks that have anywhere from between 5k-30k verts and 4k-15k tris give or take. About 12-15 chunks are visible at the same time. It seems that Voxel graphics (albeit nice looking) is very demanding performance wise.

untold moth
abstract geyser
untold moth
abstract geyser
#

Yes cubes that build the different landscapes

untold moth
#

I can't give you any advice about the visual side of things. I don't even know how it looks like now. ๐Ÿ˜…

abstract geyser
# untold moth Donno. Depends on many factors. Are the voxels cubes?

After importing from MagicaVoxel and using the Importer Asset that also optimizes the mesh, the tris and vert count is drastically reduced. So from the looks of things, it is as optimized as the algorithm that has been used could do it (e.g combining cubes on the same plane to create one giant cube or rectangle etc)

abstract geyser
untold moth
#

According do my rough math, if you have around 400k vertices a worst case scenario with unoptimized meshes, it should still be around 150 meters of view distance assuming your field of view is 90 degrees.๐Ÿค”

#

Probably even more

abstract geyser
untold moth
#

And how many vertices do they have?

abstract geyser
#

between 5-30k

untold moth
#

in 3 * 3 units? With cube blocks?

abstract geyser
#

yes

untold moth
#

are you kidding me?

#

6 vertices per face * 5 faces exposed in the worst situation * 3 * 3 = 270 at most.

#

How does a module like that look like?

#

Unless I'm misunderstanding something..?

#

Are the blocks smaller than 1 unit in length?

abstract geyser
# untold moth Unless I'm misunderstanding something..?

I think you are, One landscape module contains say 15k verts. The entire module is about 3x3 units in size. The landscape module is built with voxels. So it could be a small house and a bridge and say a few trees that make up one landscape module.

untold moth
abstract geyser
#

Just to give an example^

#

Yes the actual voxels are very tiny

untold moth
#

Can you take an example screenshot?

untold moth
#

It's like creating a nuclear reactor in your backyard with tools from the garage.

#

But maybe using lower quality blocks(increased length) for far away chunks could be a decent solution.

abstract geyser
#

I cant share an actual screenshot but I can show you how a module might look like

#

The player is seeing like maybe 10 of these modules at most

#

at the same time.

#

This with a viewing distance of 8 units

untold moth
#

Does that picture actually correspond to the view in game?

#

Is it top-down game?

abstract geyser
#

Its a VR game

untold moth
#

ah

abstract geyser
#

So you have a birds view kinda

untold moth
#

Then yeah. A LOD system for the meshes is the only thing I can think of. It can actually introduce a certain artistic effect imho. Where far away chunks have bigger blocks. Although, I imagine it will create more problems in terms of object placement and stuff...

#

Anyways, you should probably profile the game on the actual device, before making any conclusions about the performance.

abstract geyser
# untold moth Anyways, you should probably profile the game on the actual device, before makin...

I've already done that and after optimizing everything I can think of, I am getting a stable 72 fps, as long as there are not too many dynamic objects on screen at the same time. Like enemies and such that move around. At a certain point the fps could drop below 72 and get back up again. However this just shows me that I'm currently pushing it with the tris and verts count. If there was a way to reduce it or optimize the landscape to give me say 5-10% performance improvement, I could then add more enemies or more dynamic stuff in the scene.

untold moth
abstract geyser
#

Rendering is eating most of the performance

untold moth
#

If GPU is the bottleneck, then yeah, it's either vertex count or complex shaders.

#

If it's CPU, then it's not related to the geometry: probably set pass calls or draw calls.

#

Rendering is not 1 big thing. It has a lot of parts to it.

abstract geyser
#

Its the GPU yes. Profiling with the OVR Metrics tool, the App GPU T is going above 13700 microseconds at certain points which is telling me that the gpu is bottlenecking

untold moth
#

If you can't reduce the vertex count any more, try reducing the complexity of the shaders or making the gpu draw less objects.

abstract geyser
#

I am using URP Baked Lit shaders for the landscape, and simple lit for the dynamic objects

#

I am trying to use GPU instancing and such to reduce the drawcalls

#

Static batching, Dynamic Batching etc

#

I've pretty much ticked every box that should improve performance afaik

untold moth
#

Can you actually provide a screenshot of a frame from the profiler?

abstract geyser
#

At this moment no

#

Maybe later today if I have any time left, but from what I can tell from the profiler, the framedrops happen when there are too many dynamic objects in view. But reducing them could be a solution but gameplay would suffer

hidden locust
#

Would anyone know what's up with this error? I keep getting this for no reason and the code refuses to stop

#

from what I can find it's something to do with a DLL, but I'm not loading any.

#

Would be helpful as well if it said what type failed to load.

#

Types i'm using in the class where the error happens (and the one it calls) are pretty normal

untold moth
hidden locust
#

It's calling a static function from a static class.

untold moth
#

Is that your script?

hidden locust
#
public static Path<Vector2Int> Solve(Maze maze, Vector2Int start, Vector2Int end, int limit = 10_000)
#

Yeah it is

#

this is the signature

#

Path is also a class defined in the same file

#

ive never in my life encountered this error

untold moth
#

What's the deal with this:
int limit = 10_000?

hidden locust
#

ah it enters a while loop somewhere, so that is a safeguard

#

always do that with while loops

untold moth
#

what's with the underscore?

hidden locust
#

basically a comma

#

easier to read

untold moth
#

Hmmm... Seems to be a new feature in C# 7...

#

Did you try without it?

hidden locust
#

been a thing since c# 4

#

ill try it just to be sure

hidden locust
#

oh

#

thought that was added way back

untold moth
#

I wonder if that's the problem though

hidden locust
#

removed it, but didn't help

#

I think there's something wack going on with the assemblies somewhere but Unity is not telling me which type is failing

untold moth
#

What about Maze is it your class too?

hidden locust
#

yeah, that's just a struct with pure data

untold moth
#

And Path?

hidden locust
#

Path is just a Stack wrapper basically

#

lemme try without path

untold moth
hidden locust
#

nope

radiant wave
#

Is there a way to encode a string into a decimal number?

hidden locust
#

its just this

untold moth
#

@hidden locust are you using assembly definitions in your project?๐Ÿค”

hidden locust
#

no, not even

#

that's why im so confused

#

really wish it'd just give a better error message

untold moth
#

Well, try eliminating parameters of that function and return type one by one to see which one is the culprit.

#

@hidden locust Also, what's the path to the Solver script and what namespace is it in?

radiant wave
#

I want to hash a string and convert the hash into a numerical value.

byte[] sha256 = Sha256Managed.ComputeHash(Encoding.UTF8.GetBytes(ID), 0, Encoding.UTF8.GetByteCount(ID));
int value = Convert.ToInt32(sha256)```

That last part doesn't work.
hidden locust
#

It's a partial class too, but that should work right

untold moth
#

Ah, that might be relevant.๐Ÿค”

hidden locust
#

that would be odd...

devout hare
kindred tusk
radiant wave
kindred tusk
#

Hexadecimal or decimal are two different string formats for displaying the number.

#

But it's stored in binary like anything.

#

If you want to wrap the checksum into 32 bits just use a modulo

devout hare
#

Truncate the byte array into 4 elements and convert that, if it needs to be an int specifically

kindred tusk
#

Although it's probably not a good checksum...

radiant wave
radiant wave
kindred tusk
kindred tusk
# radiant wave that's fine. As long as it's deterministic

The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across .NET implementations, across .NET versions, and across .NET platforms (such as 32-bit and 64-bit) for a single version of .NET. In some cases, they can even differ by application domain. This implies that two subsequent runs of the same program may return different hash codes.

#

See the "remarks" section

tiny anchor
#

hi, i have been using a vertex and triangle array to generate meshes, but now that i am using compute shaders i want to know how i can use graphics.draw procedural or somthn to generate meshes straight on the gpu. i dont need collisions or nothing as its just a test. does anyone know how i can use my 2 arrays to draw a mesh?

hidden locust
#

@untold moth omg, i might've found the issue and it's all on me lol. I had a layout cycle somewhere in a struct

hidden locust
#

within a struct you cannot have the same struct referencing itself

#

but i did that

#

expected the compiler would give an error about that but it didn't..

radiant wave
untold moth
kindred tusk
#

Otherwise it would be an infinitely large struct!

#

No compile error?

untold moth
kindred tusk
#

If I have a mystery build freeze (seemingly an infinite loop), and I attach my debugger, how can I determine where it is? When I pause execution I just get a bunch of stack traces with thread handling stuff and no actual current line in my C# code. (I haven't actually tried pausing during the infinite loop yet because it takes 20 minutes, just experimenting with debugging a build for the first time)

leaden jungle
#

Hey I was wondering if someone here could help me identify a pattern. I first encountered it in this video:
https://www.youtube.com/watch?v=tAbBID3N64A&t=2988s
I'm talking about their bark system. In it they call it a self branching dialog tree, but also state it can be extended to do other things.. I made my own implementation in unity, I simplified and allowed it able to run multiple states/behaviours at the same time. The behaviours can also be updated in runtime so you can add and remove behaviours dynamically. In the video they call it a self branching dialog tree so I was wondering if extending it to control behaviours would make it a self branching behaviour tree? It also resembles utility function, but the conditions are all bools rather than floats and rather than analyze all cases then compare them, it returns the 1st match. In my research I have found the Fuzzy State Machine (FuSM) which might be a fit.. I'm trying to write about the pattern, but not sure how to label it.. Thanks.

GDC

In this classic GDC 2012 session, programmer Elan Ruskin shows a simple, uniform mechanism made for the Left 4 Dead series for tracking thousands of facts and possibilities, allowing intelligent characters to remember history, cascade from special to general cases, and select the optimal dialog, script, behavior, or animation for every situation...

โ–ถ Play video
granite lion
#

is there a way to make all of the objects be the same size even when theyre further from teh camera relative to another object ?

granite lion
plain abyss
#

They are the same size. If you don't want perspective, use an Orthographic camera

sly grove
#

change it from "perspective" to "orthographic"

granite lion
#

k

#

its even worse XD

sly grove
#

they all look the same size on screen now

#

that's what you asked for

granite lion
#

no , i mean i want them all to look the same size

sly grove
#

they do...

granite lion
#

they now look completely different , for example the white looks way smaller than the green 1

sly grove
#

it looks exactly the same

granite lion
#

am i blind ? XD

sly grove
#

you might be getting confused by the outlines

sly grove
granite lion
#

well , ty man , idk why i think the red 1 looks way bigger

#

am asking a friend for their opinion

compact ingot
merry robin
#

also Stereo Blindness is a thing

#

@granite lion might want to get checked ๐Ÿ™‚

undone coral
#

to make video game dialogue?

undone coral
compact ingot
# leaden jungle Hey I was wondering if someone here could help me identify a pattern. I first en...

haven't watched the full video but i get a strong feeling of logic programming (i.e. prolog)... which basically takes facts and infers possible world states by constructing and solving horn clauses. That can be combined with fuzzy and other modal logic operators to create all kinds of extremely fancy symbolic AI systems... theorem provers, action planners and the like... its the brainiest branch in academic artificial intelligence research, in Uni, 80% ultimately failed that class ๐Ÿ˜‰

kindred tusk
arctic robin
#

Hey!
I want to make a small, loop-based music creation tool in Unity. Any tips on how to visualize audio/enable on and off on a grid type system to enable/disable sounds?

undone coral
undone coral
#

i would start by looking at the asset store ๐Ÿ™‚

leaden jungle
# undone coral to make video game dialogue?

I already used it for dialog and extended it for character behaviour, but I mostly I'm trying to figure out what to call it ๐Ÿ˜› in the video they called it a self branching dialog tree..

arctic robin
#

I'm testing out development for the Hololens 2, and want to test out a loop based audio creation surface, similar to this: https://youtu.be/7Ki27CK5Je0?list=PLpyotFCx2oS9XNAFHB13V0xe7KcQzROPo&t=21

Yarr! Here you go - TWO tunes in ONE video. Grab your Octavia and use these songs when you are to farm Hydroid Prime!

I am the creator of this cover, my name in game is ShineShield
Contact me
Steam Group:
http://steamcommunity.com/groups/r666sv
VKontakte (for russian users):
https://goo.gl/ERiqQj
Facebook:
https://goo.gl/J6rnPd

โ–ถ Play video
#

Just curious where I'd start in creating something like that. Any tips at all are appreciated!

undone coral
leaden jungle
arctic robin
undone coral
#

you mean like a screenplay?

#

are you familiar with Ink?

#

you should probably use Ink for Unity if you want to write a dialog-and-action screenplay

#

like a screenwriter would

undone coral
arctic robin
#

Awesome, thanks! What do UGUI and VFX Graph add that base Unity doesn't have?

undone coral
leaden jungle
# undone coral when you say character behavior?

I have finished the whole system and works well, but I really don't know who to categorize it.. the basic pattern, I made it in unity with scriptable objects, the main core of it is a loop through a list of acts that are sorted by the number of conditions, all the condition must me met for an act to be executed and acts can be run in series or parallel, which makes me think Fuzzy State Machine possibly..

arctic robin
#

I haven't developed in it for a couple of months tbf

undone coral
leaden jungle
# undone coral so have you looked at ink?

I have looked at it before. But this does a lot more than dialog it's a whole dynamic behaviour pattern, I used it as a character controller, that controls Players and Ais

#

I was thinking of writing an article about it, but then I'm not sure what it is called or classified as..

#

in the video they use have a list of dialogs that have conditions and the number of conditions is also a condition.. but I simplified this by sorting the list by the number of conditions. Then it selects the first to match all conditions using simple fuzzy pattern matching. Acts them selves are coded to run one at a time or concurrently, which fits Fuzzy State Machine(FuSM), but if it is set up to only run one at a time I'm not sure if it would still qualify as a FuSM.

arctic robin
#

What is the best tool for working on a Unity project on multiple computers?

compact ingot
#

Does Task.Run(async () => ...); called in unity use the UnitySynchronizationContext or the default one (ThreadPool) as it would in a regular .net app?

undone coral
compact ingot
#

as in "not allocation free"?

undone coral
#

no

compact ingot
undone coral
# compact ingot but?

UnitySynchronizationContext always Thread.Sleeps(1) on the main thread which has toxic behavior in unity, whereas UniTaskSynchronizationContext uses SpinLock which has better behavior (it sleeps 0 most of the time)

#

this is why people report really weird super slow performance with UnitySynchronizationContext

#

in some cases

compact ingot
#

right, was thinking there was a problem with Task.Run

undone coral
#

i think it's because it uses unitysynchronizatoncontext

#

whereas UniTask.Void (a kind of run) doesn't have to

smoky glade
#

Conditionals are done with making formula. >=1 results is true, else false

foggy elk
zenith ginkgo
#

Materials saving as black (default colour)

graceful forge
#

Is anyone able to help with rotating a 2d array in C++? I am doing doing a blit function on pixels on the screen, and I have reference to the original sprite sheet and when I blit it to the screen I need to be able to perform an x rotation on the sprite when copying

shadow seal
#

C++? This is the Unity Discord

tropic lake
#

haven't you heard? unity and unreal have merged now

#

both c++ and c# are fully supported

shadow seal
#

๐Ÿ‘€

graceful forge
#

I mean doing it in c# would be fine I just am trying to understand the theory

#

Of copying a 2d array to another while performing a rotation

sly grove
#

It's really not complex. Just swizzle the indices. I can't be bothered to think about what the effects would be but output the indices differently and you'll get a rotation

#

e.g.:
[y, x]
[xMax - x, y]
[x, yMax - y]
[xMax - x, yMax - y]
etc

graceful forge
#

Would that be able to support all rotations or only like 90, 180. 270?

sly grove
#

90 degree rotations

#

or reflections

#

if you want anything else you'll need to do some kind of multi-pixel sampling

elfin tundra
#

it's not possible to rotate the indices of an array say 15.7 degrees bc the indices are stored in a grid formation

graceful forge
elfin tundra
graceful forge
#

The issue I'm having is I need to rotate one matrix by n degrees when copying it into another matrix

elfin tundra
#

right but if it's not a visual representation that you're rotating, it's impossible to rotate an arbitrary number of degrees bc arrays are stored in memory in grid-based rows

sly grove
#

it gets a lot more complex if you need n degree rotation. The result won't even fit into the same dimension matrix because the diagonal rectangle will need a bigger rectangle to circumscribe it

graceful forge
#

I shouldn't be rotating the source image, only performing a rotation in the process of copying each element

elfin tundra
#

i'm still confused, are we talking about an image or an array

graceful forge
#

I have an image that has been converted into a 2d array of pixels, and I need to copy that to a bigger array and perform a rotation in the process

elfin tundra
#

oh i see

#

why don't you just copy normally then rotate the image component

#

why do you have to rotate the array representation of the pixels in memory

#

just rotate the final image

graceful forge
sly grove
#

it's a starting point though

elfin tundra
#

you can't do two operations at the same time, there has to be an order

sly grove
#

also that

graceful forge
#

What I have set up is a sprite sheet, which is a 2d array of pixels, and I have a 2d array of pixels on the screen. I need to take a specific chunk of the sprite sheet, copy it to the screen while performing a rotation.

Would a solution be to cache the image I need to copy, expand the array in both dimensions and then do this rotate you linked Praetor, then copy?

undone coral
#

gameplay objective*

leaden jungle
leaden jungle
graceful forge
leaden jungle
#

I got all the info from this book

graceful forge
#

Thank you for that resource

elfin tundra
#

i'm still learning linear algebra so i forgot about that lol

leaden jungle
#

it's old from the 70s, but it has all the math for combining 2d or 3d matrix operations, such as rotation, translation and scaling into one matrix operation.

graceful forge
#

I'll definitely check that book out, thank you so much for that.

graceful forge
#

This is not for gameplay, its for a pixel graphic rendering engine

undone coral
#

sorry what i meant was, for like a retrocomputing thing?

#

if you need to transform graphics efficiently you should use a material and the methods in Graphics

#

the material can rotate, flip, etc.

#

everything you need

graceful forge
undone coral
#

using a shader

graceful forge
#

Its making this image from a console application

undone coral
#

is this unity?

graceful forge
#

No this is console application

undone coral
#

okay

#

everyone has things they say no to. for me, it's NFTs and retrocomputing

urban warren
#

Does anyone happen to know a good BVH implementation? I mostly just care about built time and test time. I don't need it to support dynamic objects.
I have implemented most of one my self, but it doesn't quite work and I have looked at the code so many times and can't figure out why.

#

(Mine uses binning and SAH, but it will always split on the first bin for some reason)

undone coral
#

i'm not sure how realtime CSG package represents geometry

#

which is way more general than BVH

#

and maybe that's interesting to you

urban warren
#

*terrain and object meshes.

#

I am making a pseudo procedural vegetation placement and rendering system.

undone coral
#

what's the big picture algorithm here

#

for how to use this datastructure to help you

urban warren
#

I would use it to generate height maps for the terrain and objects(large rocks, cliffs etc) on the terrain and then use the height maps in compute shaders to generate points to place the vegetation.

undone coral
#

isn't the terrain already a height map?

urban warren
undone coral
#

got it

#

so spell it out for me a bit more, just so i can help you

#

it'll be helpful

#

because it sounds like you can do

  1. generate mesh terrain
  2. generate a height map by applying a shader that shows world y height at the uv coordinate
  3. ...
#

you can use a triplanar material that renders y at xyz

#

or use a uv projection

urban warren
#

Ehh, no, let me explain.

undone coral
#

at y = -1

#

is the terrain concave?

#

and you want to like, fill in concave space?

#

and your goal is to "voxelize" the terrain so you can sample this concave space?

#

you have an overhang or whatever, and you want to spawn vegetation under the overhang

#

or it's just a cliff that's concave

urban warren
#

There will be a 'master' component that has a list of terrain meshes, it will generate a BVH for them and then shoot down rays at set intervals in order to get the height of the terrain and generate the height maps.
Those height maps would then be passed to Compute Shaders that would generate points (using the height maps to get the y position for the point) and meshes would then be rendered at those points.

undone coral
urban warren
undone coral
#

is the mesh concave?

urban warren
#

Just so we are on the same page, do you know what a Compute shader is?

undone coral
#

yes

#

are you trying to place the vegetation using e.g. vfx graph?

urban warren
undone coral
#

and you'd like to sample positions on the mesh, that happens to be a terrain mesh?

urban warren
urban warren
undone coral
#

the cheapest way to get the height of terrain at world xz is using a shader that renders world position y

#

using whatever camera you want

#

it would be basically instantaneous

urban warren
#

You mean like a camera facing down?

undone coral
#

yep

#

it would look like

camera.targetTexture = yourUtilityRenderTexture;
camera.Render(heightMaterial);

that's it

#

which, btw, vfx graph uses Graphics.DrawProcedural under the hood

#

so it's basically exactly the same

#

you can also use the same thing VFX graph uses to get the mesh

#

which is in the Graphics namespace

#

you can also look at its source for how shader graph will render a triplanar world xyz material

#

if you just want to use that

#

but that might be a waste of time

#

render textures are used as "utilities" all the time

#

consider you'd just need to get the texture once

#

you could certainly run it in real time if you needed

urban warren
undone coral
#

in that case, use VHACD to generate a group of approximate concave collision meshes, or as accurate as you'd like

#

because your real problem is that spooky warning about convex meshes having a limit of 256 polys

#

you can definitely just make a convex mesh collider at runtime using the built in physics collider, and you'd just be Done

urban warren
undone coral
#

it won't work with collisions

#

you need concave colliders to work with collisions, which VHACD creates for you

#

imo this BVH thing sounded like it was off the mark ๐Ÿ˜ฆ

#

it doesn't help you advance your goals

#

of course, if you only need to spawn stuff from the player's point of view

#

you can add a render pass in URP / HDRP that does world xyz

#

with your material, then spawn, and then it's occluded and LOD automatically

#

and simply look at that render pass from time to time and add in vegetation on demand

#

VFX graph already supports occlusion though

urban warren
# undone coral it doesn't help you advance your goals

It lets you do overhangs which is what I like about it. And you don't need to mess about with layers (physics and rendering both using the same layer system... just why...) But maybe it is worth giving up/working around that for the camera system....?

undone coral
#

let you do this

#

like if you add a mesh collider

#

and leave convex unchecked

#

you can raycast and get the multiple intersection points

#

you don't need a BVH if you just want to raycast a mesh

urban warren
#

What do you mean raytrace the mesh?

undone coral
#

sorry raycast**

#

you can raycast against a concave collider

#

so i don't know, you're talking about sampling this at regular intervals

#

just do it with a regular unity physics raycast

urban warren
#

Ah, I could just do a bunch of raycasts using the physics system to get the heights and then not touch it again (maybe use Jobs if I need to do something at runtime)

undone coral
#

but it depends what you mean by heights, because the height shader will do this instantaneously

#

if you don't need cliffs, that is far and away the absolute fastest method

#

it will be fast enough for realtime

#

you can also do it from any perspective camera, if you want to do a local effect

#

you can use a cubic camera if you want

#

anyway

#

i think you get it

urban warren
#

I think this for me is a bit of the project having evolved over time and what I actually need and how I am doing things has changed.

#

Thank you @undone coral this was most helpful! I am going to think over what I need exactly again and how I want to do it. Also reread some of this stuff. Would you mind if I @ you again if I have some questions about some of the things you mentioned?

#

(Also thanks for the Github link at the start, I had not seen it)

undone coral
#

sure

compact ether
#

I figured I'd ask this in here. I have a super simple game that I wanted to add some simple cosmetic upgrades to. I just want to be able to spawn into a level with a hat, glasses, etc that I selected before loading into the level.
I had 2 ideas, and let me know what you guys think. Idea 1, is just make a character prefab for each costume, because there would only be a handful of costumes, and I could just spawn the prefab in depending on the player selection. I'm assuming I could just apply an int value to the prefab, and spawn it in.
Idea 2 is having one player prefab, but having a script that applies the cosmetic to the prefab at a certain local transform point upon loading in the level. I'm assuming that is possible.
What do ya'll think? Am I over thinking this?

smoky glade
# undone coral render textures are used as "utilities" all the time

Hi so im also gonna place vegetations soon and using RT to get height map
Mechwarrior mentioned about the layer problem. But i do layer change before certain raycast and restore it all the time. Is it not the same with rendering?
Like, u change the layer right before .Render, then restore it

(And yes the physics n render layer being the same is kinda annoying..)

ancient sparrow
#

Can someone give me code of getting keyboard height in iOS. Thanks ๐Ÿ™‚

smoky glade
#

It could be. It's anything that's in "Terrain" layer

#

Yes if it's terrain i can just use the terrain's heightmap

kindred tusk
#

Managing prefab variants sucks

dusk gyro
#

how would i make 2 objects snap together if they're close enough to each other through code? been trying to figure this out for a while now but couldn't find an answer

untold moth
#

@dusk gyroSomething like that..?

if( distance < some distance)
{
  tempPos = objec1Pos;
  object1Pos = object2Pos;
  object2Pos = tempPos;
}
dusk gyro
untold moth
#

Oh wait

#

I thought you said "swap" lol

#

If you want them to snap... Well, how do you want them to snap? Just get close enough so that their colliders collide? Snap certain vertices? There is more than 1 way to snap things together.๐Ÿค”

dusk gyro
#

its in 2d btw

untold moth
untold moth
#

look up Physics2D.Raycast in the docs.

dusk gyro
#

i mean i know how to cast a ray but i dont know how to make it actually snap to the object

untold moth
#

You get the position of the hit and use it to set the position of the silhouette object.

dusk gyro
#

wouldn't that snap the center of the object to that position?

untold moth
#

@dusk gyro Then add some offset.

#

Or change the pivot point of the silhouette prefab/object

dusk gyro
final kindle
#

How should you handle unit tests designed to give an error? For example if you were to test that giving a grid class a negative size log errors? For me the log is making the test quit and fail.

fresh salmon
#

Depends on your unit test library. For NUnit I remember being an Assert.ThrowsException<T>() method where T is the exception you expect to be thrown

final kindle
#

Ah. Thank you. I was expecting to have to silence the logger or something. I'll have a look at that.

fresh salmon
#

Otherwise making your own generic version of that method wouldn't be hard, a try-catch block where you attempt to catch catch (T) (don't forget the where T : Exception constraint), and after that catch (Exception) if it threw anything else

final kindle
#

Maybe, though I don't like the idea I'm having to change the code to do the testing like that.

urban warren
plush lion
#

Hey, what would be an elegant way to access prefabs during tests in play mode? Best I could find is AssetDatabase.LoadAssetAtPath, but it stops working whenever the object is moved

#

There's no way I'm the only one that had this issue

#

Yet google finds nothing :(

bleak steppe
plush lion
#

How do I know the guid of an asset ?

bleak steppe
#

open its .meta file and the guid will be there

plush lion
#

Thanks!

hot linden
#

Hey there. How would you handle mirroring horizontally a 3d character for a 2d platformer ?

  1. duplicate the whole animations tree for a right and left version (seems tedious)
  2. mirroring everything programmatically

I suppose 2. is the best way but if someone has a reference for that, I'll be glad to know about it, right now I can't seem to find a solution

#

For reference something like Ori 2 does

sly grove
hot linden
#

it is angled

#

so it is no more readable

#

maybe Street fighter is a better reference

#

the character is in a fighting stance, when rotated 180, his face is hidden and strong arm is no more visible

#

nvm found a way => if I invert the z scale of the parent transform it seems to work ... animation is doing strange things though

undone coral
hot linden
#

so I need to duplicate every animation ?

undone coral
#

no

hot linden
#

I've tried something else and animation is less weird : inverted x axis scale and rotated on y by 180

undone coral
#

or look up if an asset does this for you

#

in maya you can do this

#

it supports a real mirror operation on bones and geometry

hot linden
undone coral
#

then for bones animation, you need it mirrored too

hot linden
#

but then I would need to duplicate every animation still isn't it ?

undone coral
#

yes

hot linden
#

hmmm ...

undone coral
#

what do you mean animation

#

is this a 3d character?

hot linden
#

yes

#

elseway I would just have to negate the scale on x

undone coral
#

so far

#

a lot of things may glitch with whatever that kind of scaling is called

hot linden
#

well ... I'll keep on digging then

#

I'm pretty sure there's a way to handle that without duplicating every animations

#

my DRY sense is in high alert

formal kayak
#

hello

#

got this code

elfin tundra
#

what's the issue

tropic lake
#

think they're gonna say that

formal kayak
#

how to set notepad into foreground?

elfin tundra
#

idk if you can do that in unity

#

why do you want to do that anyway

formal kayak
#

it's very important, not with notepad, but another software wich is running

elfin tundra
#

what is the software

#

and again, why are trying to do that

formal kayak
#

because I'M developing a non-game experience and I need to change between windows

elfin tundra
#

don't develop a non-game experience in unity

#

unity is for making games

tropic lake
#

no guarantee it will work in unity

formal kayak
#

thanks

tropic lake
#

generally i don't think unity is the best for non game experiences

#

something like a wpf app could work better

#

and it also uses c#

elfin tundra
#

agreed, that's what i was saying

formal kayak
#

my program has to display 3d graphics

elfin tundra
#

use c++ then

formal kayak
#

I'm more familiar with unity ๐Ÿ™‚

elfin tundra
#

ok so get more familiar with c++

#

at some point you weren't familiar with unity and now you are

#

so you can get familiar with the tools you need

harsh grotto
elfin tundra
#

i don't think i've seen a single normal application made in unity

#

give me a few examples and i'll take back everything

harsh grotto
#

pretty sure wallpaper engine runs on unity

tropic lake
elfin tundra
harsh grotto
#

yes, which implies some sort of unity integration

elfin tundra
#

right so that doesn't count as a normal application that has nothing to do with unity

harsh grotto
#

regardless, there are plenty of non game companies that use unity for non game related things, no point gatekeeping how people use it

elfin tundra
#

yeah i guess

#

i just hadn't seen any, and regardless, c++ is much more widely used for everyday applications

plain abyss
elfin tundra
#

oop

#

i am very sorry

#

i will point out that unity was made in c++ tho

harsh grotto
#

my job uses it for visualization too

elfin tundra
#

damn

plain abyss
#

C++ scares me

elfin tundra
#

i like it more than unity for a lot of things but c# is a better general-purpose language imo

#

just not as flexible for applications all the time

plain abyss
#

But I'm totally fine using Java to convert an AutoCad drawing into a GLTF model and dynamically loading that into a Unity scene at runtime for realtime 3D visualization of a blueprint ๐Ÿ‘

compact ingot
compact ingot
elfin tundra
#

thanks but i've already been disproven lmao

#

(but btw both of those apps relate to games)

compact ingot
#

so you mean don't use unity for apps that do not leverage media... i'd agree

elfin tundra
#

yeah

#

like idk a text editor or something

#

you wouldn't make that in unity

compact ingot
#

but i know a company who wanted to just do that.........

elfin tundra
#

oof

compact ingot
#

yeah..

#

took them a year to realise it is hopeless

#

the guy who initiated it now has 1 year of unity experience

elfin tundra
#

guys i got the point

#

i'm sorry

#

i made an assumption, now i have learned

urban warren
#

Sorry, didn't mean to pile on.

undone finch
#

I have made own developer console in my game (I needed it because it is multiplayer game), is there some way to catch Debug.Log functions executing and "redirect" it for my own console logging?

unkempt nova
#

Yeah, there's a callback you can hook into, lemme find it

#

@undone finch

kindred tusk
#

Oh I didn't know about that!

sturdy edge
unkempt nova
#

Yeah, first link wasn't what I used, but looks like you just need to match the signature

#

Not sure tbh

#

But since it's a delegate, you can use

private Application.LogCallback myLogCallback;
void Awake() {
         Application.logMessageReceived += myLogCallback;
}
``` to simplify things
#

Better example: ```cs
public class LogTest : MonoBehaviour
{
private Application.LogCallback myLogCallback = (condition,trace,type) => {
Debug.LogFormat("Condition: {0}, Trace.Length: {1}", trace.Length, type.ToString());
};

void Awake() {
    Application.logMessageReceived += myLogCallback; 
    Debug.LogFormat("Test!");
}

private void OnDisable() {
    Application.logMessageReceived -= myLogCallback;
}

}

#

@sturdy edge

undone finch
#

Hell yeah now debbuging on multiplayer will be easier

sturdy edge
unkempt nova
#

One I used made it very easy to make your own commands too

undone finch
#

I think this is the best way to learn

#

But maybe I am wrong

unkempt nova
undone finch
#

thanks anyway

unkempt nova
#

I highly recommend it

undone finch
#

I am just doing some game without intention releasing it to public, I very like gamedev and this is not my job. It is just so satysfing and its the way I spend my almost all free time ๐Ÿ˜„

unkempt nova
#

Same. GL HF

silent dagger
#

๐Ÿ‘‹ any good math brain can help me with some calculation?

#

I'm trying to convert world position into pixel position

#

I've a custom splatMap, and I need to convert object position into corresponding pixel inside the texture

#
    {
        if (pos < 0) pos *= +1; // Convert value to positive

        var p0 = Mathf.RoundToInt(pos);
        var p1 = p0 %terrainSize;
        var p2 = p1 / terrainSize;
        var percentage = p2 / terrainSize * 100;
        return Mathf.RoundToInt(textureSize / 100 * percentage);
    }```
#

this is the non-working code ๐Ÿ˜•

#

๐Ÿ™ PLEASE

#

the idea was to run the method for each axis

compact ingot
# silent dagger ๐Ÿ™ **PLEASE**

something like this maybe (pseudo-code):

// for a flat texture facing World-Y
Vector3 worldPosInSplatSpace = Vector3.ProjectOnPlane(worldPos, Vector3.up) * texelsPerUnit + splatWorldOrigin;

// or more generic, if splatOrigin has/is a transform/TRS-matrix
Vector3 worldPosInSplatSpace = Vector3.ProjectOnPlane(
    splatOrigin.transform.worldToLocalMatrix.MultiplyPoint(worldPos),
    splatFacingNormal
) * texelsPerUnit;

results are vec3, so you have to ignore whichever component is orthogonal to your tx.plane

silent dagger
#

WOW that's looks nice ๐Ÿ˜„
thanks ๐Ÿ™‚

#

I guess the former should work, appreciation ๐Ÿป

silent dagger
#

Working great ๐Ÿ˜„

misty glade
#

Best practice question. I have a game object which may be disabled in a screen by default. When it's "initialized" (not Instantiated(), but rather initialized by me when I know some details about the object), I get the Image component using GetComponent<Image>() and then set the image accordingly. I can't do the GetComponent<>() call in Awake() since Awake doesn't get called on inactive game objects (I didn't realize that, so this was a fun bug to find ๐Ÿ› ).

Where do you typically, or best practice make this call to GetComponent? I don't want to create external dependencies on the object to initialize it before initializing it, if that makes sense.

See below. I can just set the "Person" of this display gameobject and everything "works", unless the gameObject is inactive - in which case Awake() isn't called first and I get the null reference exception as commented..

        private Person _person = null;
        public Person Person
        {
            get => _person;
            set
            {
                if (_person != null)
                {
                    _person.OnPersonUpdated -= UpdatePersonIcon; //unsub from the old person event
                }
                _person = value;
                _person.OnPersonUpdated += UpdatePersonIcon;
                UpdatePersonIcon();
            }
        }

        private Image _icon;
        private void Awake()
        {
            _icon = GetComponent<Image>();
        }

        private void UpdatePersonIcon()
        {
            ... etc ...
            _icon.overrideSprite = Resources.Load<Sprite>($"Graphics/Sprites/People/{iconName}"); // null reference exception if the game object is inactive while trying to set this
        }
drifting galleon
#

OnEnable()

misty glade
#

I mean, I could make an Initialize() method that gets called in Awake() and before UpdatePersonIcon() i suppose, but that feels sloppy

#

that's the same as the Awake() problem, though - I can UpdatePersonIcon() before that's called

#

(in fact, that's my workflow - Create this game object, set the Person, then enable it)

#

Actually - better (and maybe simpler) question - is there any script activity at all on a monobehavior that's inactive?

#

like, I could just do:

private bool _isInitialized = false;
private void Initialize()
{
  ... blah blah blah...
}

// and then anywhere I need an element:

if (!_isInitialized) Initialize();

but this doesn't feel great/clean to me, I suppose?

long ivy
#

why do the GetComponent in Awake at all? Make _icon a serialized field. Alternatively, making UpdatePersonIcon a no-op unless icon is set, and call UpdatePersonIcon inside Awake

misty glade
#

I guess I was hoping there was an Awake() analog that got called when the actual game object was created/instantiated/whatever

#

I could make it a serialized field, but I generally try to keep the public/serialized fields to a minimum unless something else in the app needs to set it

long ivy
#

you can make it private and serialized

quasi granite
#

Okay, this is very, abstract.
I Am creating a fighting game. Near the beginning I was convinced that using Unity Colliders for the hitboxes and hurtboxes would be innefficient because of the sheer number of frames and hitboxes displayed each second by each player would make it irrealistic to instantiate all the different Collider Components exactly when I need to, and also the hit detection would be handled by the physics system, which would make hit detection not be handled percisely with update and would be hell to manage both locally and through network.
I ended up creating my own hitbox and hurtbox system which is purely numbers with min and max coordinates to a origin transform position. Its very efficient, but Im wondering if i was correct in my assumption that using colliders wouldve been less efficient. Am I incorrect?

misty glade
#

In this case, the Icon itself is an internal detail - the only public element of this game Object is the "Person" - the display element displays a whole bunch of stuff, person name, hit points, rarity, and icon

#

Ideally I only want the Editor to show "Person" in the fields - my understanding is that even private serialized fields show up in the editor? (I haven't really used them before)

#

I could do that, though.. I mean, I suppose there's no real reason for me to be GetComponent()-ing at runtime, it's not like I'm adding the component programmatically

#

That's actually probably the best reason to just serialize it and set it in the editor (so I'm not fiddling with bugs/shit like this down the line)

misty glade
# quasi granite Okay, this is very, abstract. I Am creating a fighting game. Near the beginning ...

Potentially, but "premature optimization is the root of all evil" - Using unity's colliders would likely have saved you (or will save you, if you revert) tons of time and effort and may have actually been good enough. I suspect that a fighting game would be totally fine. A physics game with hundreds or thousands of hitboxes might benefit from a roll-your-own approach, but even then, you're gonna be doing a lot of work and ... hard work, lots of debugging physics, etc.

misty glade
quasi granite
misty glade
#

Yeah - I mean, same thing - you'd just have a collider but not the physics elements (rigidbodies)

quasi granite
#

would using colliders ensure that I am able to handle hit detection the exact frame that the overlaps happen though?

drifting galleon
quasi granite
#

dots? dangit theres still so much i dont know about unity

misty glade
#

don't use DOTS imo :p

drifting galleon
drifting galleon
misty glade
#

pardon my emote-french ๐Ÿ™‚

#

I dabbled in DOTS then.... undabbled

drifting galleon
misty glade
#

yeah i mean, I might come back to it someday but I'm ... tied to my architecture and haven't written any threadsafe code

#

ie - I depend on single-threadedness atm

quasi granite
#

I already created my hitbox system, and if i set the framerate to 144 and spam thousands of hitboxes per second with no optimization on which hitboxes will actually be eligible I see no framedrops whatsoever, I think im just gonna stick with what i have regardless of what would have/could have been more efficiet.

misty glade
#

external libraries generating read only lists and passing them around, etc

misty glade
quasi granite
#

yea this took a whole month and a half, not worth the development time

#

Good learning project though

misty glade
#

there's a recent post on r/programmerhumor that's like... Computer Scientists write sorting algorithms, Programmers call .Sort(). I want to be a programmer and just call the oncollision events ๐Ÿ™‚

#

I don't want to write any trigonometry - I'm getting too old for that now ๐Ÿ˜›

#

I just am not interested in debugging really fiddly details and stuff

quasi granite
#

its purely boxes, I didnt worry about trigonometry

misty glade
#

I'm just coming out of writing some debugging statements that are already kind of gnarly because my game state is .. complex

quasi granite
#

that is a unique hell to live in, good luck to you

misty glade
#

match-3 meets hearthstone

#

(each player has a grid instead of a hand, they can match-3 or "play" items to their field)

#

but the match-3 programming was .. harder than i expected.. and I believe that I'm a quite good programmer (who doesn't, right?)

#

recursion bugs ๐Ÿคฏ

quasi granite
#

i honestly have no idea what tf this is this is terrifying

#

I am by no means an experienced programmer. I am creating a game and learning as I need to.

misty glade
#

the paste is my server console output for this:

#

each player gets a grid, can merge-3 more items, play them to their field, and they attack the opponents "crew" (the 3 guys at the top)

#

pardon the developer art - the art/UI guy is still working on mockups for this

gloomy nova
#

complicated question, but I'm thinking about how I can code behaviors and then use them as pluggable objects in scripts

for example, say I have a "Wander Area" behavior, a "Flee From Target" behavior, and an "Attack Target" behavior. I don't need these as scriptable objects - I just need a way to reference these behaviors in a script or scriptable object, because let's say we have a deer and a wolf, and both use "wander area", but in the deer's case, it will use "flee from target" when the player moves into range, while the wolf will use "attack target" under that same condition.

I've solved things like this in the past ||using reflection to obtain identifiers for each type of behavior at runtime, then defining each unique entity's behavior graph in a markup file, then creating a parser that reads through that markup file (thinking XML in this case, since .NET includes pretty straightforward XML parsing) and creates a behavior controller. ended up extending this to also define other parameters about the entity, so that all information about "deer" and "wolf" is contained within deer.xml and wolf.xml.|| spoilered for the sake of textwall

#

my thing with Unity is that it supports SOs and prefabs, and I'd like to take advantage of that (much simpler to use a "deer" prefab with a configured behavior controller attached than to just eschew the entire system and use XML to define npcs)

urban warren
gloomy nova
#

so my question is basically: how simple would it be to load up all coded behaviors to create a behavior graph in-editor? I'm not particularly interested in writing a complex graphical utility - all I really need to do is be able to script a BehaviorController that lets me select a behavior, fill out parameters with property drawers, and define transitions out of that behavior into other behaviors

gloomy nova
#

delegates would probably be very useful there

#

what i'm looking at is effectively a scriptable FSM

#

I could actually probably get away with using a Mecanim animator as a regular state machine graph if I wanted to hack it, tbh, since I plan on using Animancer instead for the actual animation side of things

#

but the API for the Animator class is uhh

#

lmao

urban warren
#

FSM aren't that great for AI normally.

gloomy nova
#

depends on what you want to do

urban warren
#

But beyond that I'm not sure what the question is now?

gloomy nova
#

and what kind of AI you're after

urban warren
gloomy nova
#

so what I'd like to do is:

  • code parameterized behaviors (BehaviorWander, BehaviorAttackTarget, whatever)
  • be able to select those behaviors and configure their properties for that instance in a BehaviorController through the editor
  • specify transitions into other behaviors from each behavior, if applicable
#

The alternative to this, which I have experience doing outside of Unity, would just be to define everything in an XML file, parse that, and create templates for entities that are then used when they're spawned.

#

and iirc you can serialize xml/text file fields, so for something like a spawner, it would be simple enough to just drop in the file

#

just curious, what do you typically use for AI?

urban warren
gloomy nova
#

oh i didn't even realize there was a full ai section lmao

#

nah I don't need code examples

#

correction - I understand the concepts and how to code them, it's working with the Unity API that I'm having the issues with

chrome kraken
#

ttrying to learn unirx

i am getting this error, can anyone tell me how to properly assign reactiveproperty?

royal raft
#

anyone know how to convert Player.Realtime.player [] to player[]

olive totem
#

@chrome kraken you might have to pass in a type because from the looks of it that Linq expression returns a ReactiveProperty which seems to be a generic type just going by your public variables

broken socket
#

what does the error says ?

olive totem
#

Looks good indeed except on the website they use actual properties, not sure how much that should matter however

#

Not familiar with this framework

broken socket
#

me neither ๐Ÿคทโ€โ™‚๏ธ

chrome kraken
#

so i tried to use same as gitbut ex to use property isntead of memebr variables

#

i also tried to cast it

#

but it crashes after i enter unity

#

after casting der is no error in IDE.. but once i play the scene.. i get below error

PlayerHealth..ctor (System.Int32 maxHealth) (at Assets/Scripts/Player/PlayerHealth.cs:17)
PlayerController.Start () (at Assets/Scripts/Player/PlayerController.cs:17)```
#

feeling so dumb... not able to figure out for 2hrs now ๐Ÿ˜ฆ

chrome kraken
#

i am really dumb.... i looked everywhere expect pressing f12 on ToReactiveProperty() method... forgot i can access source code LOL..

this solved the issue..seems the github readme is not update

compact ether
#

Question. How do I find a game object with a specific tag, if it's a child of a parent object? My script was working when my Camera was just it's own object, but once I attached it to a parent (for other functionality I needed) my script can no longer find the object anymore, and throws a null reference. Mind you, nothing has changed on the Main Camera object, but it's hierarchy.

sly grove
#

It only cares about the tag

#

What object are you trying to find and what code are you using to try to find it?

harsh current
#

I'm trying to delay release of addressables, something like:
` private bool _releasing;

public async void Load()
{
  if (_releasing)
  {_releasing = false;}
  else
  {
    _handle = _assetReference.LoadAssetAsync<Sprite[]>();
    _value = await _handle.Task;
  }
}

public async void Release()
{
  _releasing = true;
  await Task.Delay(TimeSpan.FromSeconds(5.0));
  if (_releasing)
  {
    _releasing = false;
    Addressables.Release<Sprite[]>(_handle);
  }
}`
#

The problem is, I want to kill the previous asynchronous call if it tries to re-release after a short load

#

like release-load-release fast

#

it should cancel the previous release and restart the "counter"

#

any tip?

midnight violet
harsh current
#

Cancellation tokens is exactly what I was looking for. I knew about them, just didn't remember. Thanks!

harsh current
#

This did the trick, so it only releases the addressable after 5s.
`private CancellationTokenSource _loaded;

public async void Load()
{
if (_loaded == null)
{
_handle = _assetReference.LoadAssetAsync<Sprite[]>();
_value = await _handle.Task;
_loaded = new CancellationTokenSource();
}
else
{
_loaded.Cancel();
_loaded.Dispose();
_loaded = new CancellationTokenSource();
}
}

public async void Release()
{
try
{await Task.Delay(5000, _loaded.Token);}
catch (TaskCanceledException)
{return;}
Addressables.Release<Sprite[]>(_handle);
_loaded.Dispose();
_loaded = null;
}`

indigo turret
#
using System.Collections.Generic;
using UnityEngine;

public class Mouselook : MonoBehaviour
{
    // Start is called before the first frame update

    public float mouseSensitvity = 100f;

    public Transform playerBody;

    float xRotation = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitvity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitvity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseY);
    }
}```



what is the problem i can just look up and down and not right and left even if i see the number in the x is changing
devout hare
indigo turret
#

ok ๐Ÿ˜ฆ

misty glade
#

Debugging a nasty issue for 2 days, could use thoughts.

I have a data structure called a GridItemDictionary that has a List and Dictionary internally for holding items on a grid (the dictionary is for fast lookups based on (x,y), the list is for enumerating the items on the grid by Id).

I keep this data object in memory on the server and on the client(s). It's a turn based game, and during a turn, many things can happen to the grid (new items get added at new locations, items get upgraded, etc). It's impossible/illegal for two items to exist in the same (x,y).

When the server sends updates to the clients, it does so in the form of a list of "battle actions" (9 types, currently, I expect there to be many more) - some of which are BattleActionNewGridItem or BattleActionUpgradeGridItem or BattleActionDestroyGridItem. When the message is received by the clients, they update their internal data structure, animate the changes and then destroy/change the game objects (since the animations take time - the game objects aren't destroyed immediately when the server tells them to).

Somehow, and very rarely, I'm getting ArgumentExceptions from the Dictionary when I try to add an item that already exists in the dictionary. I cannot figure out how to reproduce the issue, and I am fairly lost in even knowing what the root cause "area" is (animation delay? network issues? actual game object integrity/logic issues?).

I can provide any source code you want to see.. here's kind of a list of the relevant classes:

  • BattleManager (client logic manager)
  • BattleScreen (client UI)
  • DudeGridRenderer (client grid item - yes, the name is awful)
  • GridItemDictionary (data object representing all items on a grid)
  • Battle (server "battle" object, contains GridItemDictionaries and all battle-specific stuff)
  • ServerBattleManager (primary server logic)

Thoughts/strategies welcomed.

#

I can't even reproduce the issue 100% ๐Ÿ˜

#

Actually I'll just go ahead and start pasting the code from the above classes in case you're bored and wanna have a whack at armchair debugging.. or feel free to just point and laugh at me. ๐Ÿ™‚

long ivy
#

are your clients applying updates right away, or do they queue them up and replay them client-side?

misty glade
misty glade
#

It's... complicated, unfortunately.. even though I have tried to keep it as simple as possible to avoid bugs like this but... somehow I've stepped in the poo anyway.

misty glade
#

Hm.. I did find one small bug that... may be related? BattleScreen.cs line 150 - I should only start the queued coroutines if the queue was empty before adding one, not if the count is greater than 0 - if I queue a bunch of coroutines at once (which I do) then they all start animating immediately. There may have been situations where the grid items didn't get deleted or something, leading to data integrity issues.. shrug

blazing osprey
#

I'm making (or trying to) make a game where the user can build train tracks/stations and I'm having difficulties figuring out how to
a. spawn a train at the station(I could probably make a script and attach to the train station)
b. make said train follow the tracks, and
c. Check if there's a railway connecting two stations, so that the stations know if they should spawn a train(I don't want the train running out of track in the middle of the map)

Obviously this is a major part of the game, so any help is appreciated. I thought about using A*, but couldn't find a way to do a. and b. with a".

urban warren
blazing osprey
#

Ya I guess I solved a while I was typing it

#

Iโ€™m kinda new to unity, so could you point me towards a tutorial about splines?

#

I have a small understanding about splines, but I donโ€™t rly think it fits in this context

blazing osprey
#

So I have two pieces: straight tail and curved rail 90 degree turn

sly grove
urban warren
blazing osprey
#

The thing is, the user can place tracks anywhere on the plane, except for on top of another track

#

So how would I tell if there is a path connecting two stations?

blazing osprey
#

No

urban warren
sly grove
blazing osprey
#

I mean itโ€™s precise to 0.25 units

blazing osprey
#

Iโ€™m really stuck

sly grove
#

I recommend doing some research into graphs and algorithms like Depth first search

#

And breadth first search

#

Once you get an understanding of that you can think about how to model your tracks as a graph and it should become pretty easy

#

You will want to have a strong understanding of that area to pull this kind of game off effectively

urban warren
#

What Praetor said, and for actually connecting the tracks together you will most likely want a sparse matrix. (Someone can correct me if there is a better way)

blazing osprey
blazing osprey
urban warren
sly grove
blazing osprey
sly grove
#

Yeah

blazing osprey
#

Ok Iโ€™ll take your word for it

urban warren
#

Well you don't even need to do it every time you place a track, only when connecting two tracks.

sly grove
#

It's basically O(n log n)

blazing osprey
sly grove
#

As long as you don't have 10000 tracks it'll be fine

urban warren
blazing osprey
#

Ok

#

Iโ€™ll google it

#

Thanks guys you helped a lot

#

Guys/girls

blazing osprey
#

ok Iโ€™ll look when I get home

#

Thx

urban warren
#

The idea is that each time you place a track you convert it's position to a 2D index, and add it in the sparse matrix. You can then do index.x + 1 to get the track (if any) that is next to it.

blazing osprey
#

Huh thatโ€™s smart

#

Also idk about this assumption but would it also be easier to save player progress with sparse matrix?

urban warren
blazing osprey
#

Well rn Iโ€™m just spawning prefabs I guess thatโ€™s not really smart in all aspects

#

So sparse matrix is better than GOs

urban warren
blazing osprey
#

Ye

#

Sorry for late response

#

I guess since I just started making the fame a week ago I havenโ€™t really been thinking long term

rapid wolf
#

you guys is there any way to get access to the network details in unity?

vestal heath
#

What kind of network details

undone coral
#

my guess is that you are moving an object without updating its position in the grid

undone coral
rapid wolf
undone coral
#

but what's your goal?

rapid wolf
#

Im currently working on a unity powered os

#

and a network reading for certain things would be a nice touch

undone coral
rapid wolf
#

yes

undone coral
#

on linux you can stat files

rapid wolf
#

it is

undone coral
#

there's lots of stuff on google for this ๐Ÿ™‚ good luck!

rapid wolf
#

thx ill do my research.

compact ether
#

I've been making some phenomenal progress on my current project, thanks to this Discord. I can't thank all of the regulars on here enough for the help.
I had a question regarding level selection/progression. At the end of my level, I have a quit, restart, and next level button. I want the next level button to obviously go to the next level, but what should I do if there is no next level? Should I run a check to see if my string is valid, and then perhaps either grey out the button or return to the menu? I'm trying to make the script modular, so I could plop it in any level, and also work if I expanded my level count.
Edit: And to add on, is there a way to verify if a level name string is valid before trying to open the scene? Would that just be a null check or something?

misty glade
misty glade
#

Er, uh, SetEnabled() I believe - i forget the actual property

#

Are you doing scenes as levels, and the button basically just loads the next scene when pressed?

undone coral
#

because it sounds like right now you are doing move as

#

the caller has to remove a grid item, then add the grid item back in

misty glade
#

No.. the client is free to set the grid items x and y.. the container places no faith in the (x,y) lookup dictionary - if it fails to find on that, then it discards rebuilds that dictionary.. clients don't remove/readd grid items to the container

undone coral
#

well, that's why you're getting exceptions

#

because it's assuming something is immutable that is not

#

i assume things can move around in your game

misty glade
#

aye, can and do

#

I'm ... not understanding your stance though... like, my game doesn't assume anything in the container is immutable - in fact it explicitly mutates them constantly

undone coral
#

a cache key is supposed to be immutable

misty glade
#

the container just provides ... extended functionality than List does

undone coral
#

which is why i am encouraging you not to use a cache

#

not to do that as the pattern

#

you shouldn't "rebuildcache"

misty glade
#

cache might be a bad word for the pattern I implemented.. maybe lookup table is better?

undone coral
#

you should just set the dictionary's values on Add, Remove and Move

#
        /// <summary>
        /// Add a single GridItem to the GID.
        /// </summary>
        /// <param name="gridItem"></param>
        public void Add(GridItem gridItem)
        {
            _gridItems.Add(gridItem.Id, gridItem);
            if (_gridItemLookupCache.ContainsKey((gridItem.X, gridItem.Y))) // cache collision
            {
                RebuildCache();
            }
            _gridItemLookupCache.Add((gridItem.X, gridItem.Y), gridItem.Id); // ArgumentException throw is OK - data is corrupted (can't be duplicate X,Y in a Grid).
        }
#

this is very dubious

#

it's also where you're getting the exception

misty glade
#

Hm.. I understand that, I'm just not sure I understand why - since the collision/exception is very rare

undone coral
#

everything points to a bug where the caller is mutating grid item

#

and not update the lookup cache

#

because it doesn't have to

#

i can't see if grid item is a struct

misty glade
#

Right.. I mean, the caller doesn't have any info about the lookup cache..

undone coral
#

is grid item a class or a struct?

misty glade
#

it's a class, but could be a struct

undone coral
#

i think you have to write Move on this class

#

and rewrite it

#

it is buggy

misty glade
#
    public class GridItem
    {
        public int Id;
        public int X;
        public int Y;
        public GridSquareContents Contents;
        public int DestroyIntoId;
        public int DestroyIntoX;
        public int DestroyIntoY;
        public int ChainId;
        public int CurrentHP; // 
        public int MaxHP;
        public bool C1; // belongs to C1
    }
}```
undone coral
#

you probably have a bug of the form:```
gridItem.x = newX
Remove(gridItem.Id) // wrong
Add(gridItem) // bad

misty glade
#

GridItem is used extensively through the game - the GridItemDictionary is .. a superset of List<GridItem> where I can perform fast random access on X and Y instead of I

undone coral
#

where the Add's error is a red herring

misty glade
#

Hm.. so I "can't" remove an item by X, can only remove by Id

undone coral
#

yes but you see what i'm saying

#

you mutate it before you remove it or something

#

i'm trying to tell you what the bug probably is

#

you have to implement Move on this class, trust me

misty glade
#

Yeah - trying to think it through

undone coral
#

this class needs to be rewritten

#

i would do something of the form

int Add(gridItem) {
  assert that the grid item's ID is invalid
  assert the position is unoccopied
  assign it an id
  place it
  mutate the grid item's id field
  return the id
}

GridItem Remove(int id) {
  remove the grid item everywhere
  mutate the grid item's id to -1
}

Move(int id, destination) {
  move the grid item
}

etc. etc.

#

you can maybe make the grid item's x and y location only accessible to this class too

misty glade
#

Thinking on that - that's a possibility but that would require

undone coral
#

that can be a little more cumbersome though

misty glade
#

yup

undone coral
#

anyway you got it ๐Ÿ™‚

misty glade
#

X and Y would need to become private setters on GridItem, which I think might be OK since they don't exist with an X and a Y when they aren't on a grid, obviously

#

But I'm still struggling with the "you have to rewrite this" because I'm not sure what I would change right now on the GID

undone coral
#

yeah

#

maybe start with the Move

misty glade
#

I'm not seeing what's buggy (yet)

undone coral
#

that will help

#

and port all the places you move to use Move

misty glade
#

I also sorta don't want to do that - because there's a pretty big refactoring cost to implementing Move

#

I'm talking a 40k line codebase across 3 libraries

undone coral
#

that should be evidence that you probably have a bug there

misty glade
#

it's not impossible but.. just a big piece of work and I'm not sure the bug is .. there

undone coral
#

somewhere, something is changing the position before Remove

#

and then the lookupcache will remove the wrong item

misty glade
#

hm.. it can't, though

undone coral
#

why not?

misty glade
#

it only ever removes on Id

undone coral
#

if (_gridItemLookupCache.TryGetValue((gi.X, gi.Y), out int cacheId) == true && cacheId == Id) _gridItemLookupCache.Remove((gi.X, gi.Y));

#

i don't know, looks like the Ids might be bad too

#

i guess, that's what's happening right?

#

i don't know what to say

misty glade
#

Ids are immutable - i could make them explicitly so

undone coral
#

clearly the grid item is being mutated in a toxic way

misty glade
#

Yeah, I mean, you're not wrong, something smells in this general area

#

I just .. am not sure what

#

and the fact that it works 99.99% of the time is what's really getting me

#

Like I can have a session where I play for hundreds of adds/removes/moves without any issue whatsoever

#

then randomly get this exception

#

I mean, I've gone as far as overriding ToString to print out what the grid looks like at any given point in time

#

ie:

#
        Grid:
                +-------+-------+-------+-------+-------+
                |       |       |  (4)  |  (1)  |       |
                |       |       | ID 12 | ID 16 |       |
                |       |       | CID 0 | CID 0 |       |
                +-------+-------+-------+-------+-------+
                |  (1)  |       |       |  (3)  |       |
                | ID 20 |       |       | ID 18 |       |
                | CID 0 |       |       | CID 0 |       |
                +-------+-------+-------+-------+-------+
                |  (2)  |       |       |       |  (1)  |
                | ID 11 |       |       |       | ID 13 |
                | CID 0 |       |       |       | CID 0 |
                +-------+-------+-------+-------+-------+
                |  (1)  |       |       |  (4)  |       |
                | ID 24 |       |       | ID 14 |       |
                | CID 0 |       |       | CID 0 |       |
                +-------+-------+-------+-------+-------+
                |       |       |       |       |       |
                |       |       |       |       |       |
                |       |       |       |       |       |
                +-------+-------+-------+-------+-------+
#

which looks amazing if I do say so myself ๐Ÿ™‚ ๐Ÿ™‚ ๐Ÿ™‚

#

but so far haven't tracked down any root cause or issue

compact ether
misty glade
#

yeah that's fine, no problem with that

#

and if so, disable/make-non-interactive your button, depending on your preference

#

(maybe make a special glowy button that goes to the credits, or something)

compact ether
misty glade
#
Scene next = SceneManager.GetActiveScene().buildIndex + 1;
if (!next.isValid())
{
 // set the button to inactive/different button/etc
}
#

sorry - isvalid is a method, not a property

compact ether
#

Ah thank you

misty glade
#

edited to add the ()

compact ether
misty glade
#

i was just copying your code - i don't know the actual call for getting the next scene.. lemme dig for a sec

#
Scene next = SceneManager.GetSceneByBuildIndex(SceneManager.GetActiveScene().buildIndex + 1);
if (!next.isValid()) { ... }
#

should work

compact ether
#

Ah, I'll be totally honest, I didn't think Unity would return a dang int for that function haha. If it worked how we thought, it would be golden haha.

misty glade
#

yup.. as always, consult the API docs ๐Ÿ™‚

austere jewel
#

It says index, why would it be anything but an int?

compact ether
#

Why comment if you aren't going to be constructive in the slightest?

austere jewel
#

I'm wondering why you would think it would be anything else, I'm not trying to be antagonistic, I want to know

compact ether
#

Because I'm not a good programmer? Is that a good answer for you?

austere jewel
#

That doesn't have any explanatory power, so no

compact ether
#

Good lord, how are you a mod lol

austere jewel
#

Are you alright? I just want to understand your mindset, you're not being attacked here. It helps me to know why you would think something like that so I can help others

untold moth
#

I'd like to point that "I'm not a good programmer" is not a great excuse to use in #archived-code-advanced ๐Ÿ˜…

compact ether
#

Here's my thought process. I would think it would return the string name corresponding to the index number. So say index number 10 is "Scene10", so the function would just return that string name, considering you use strings for most of the Scenemanagement API to work. It would just make it easier for both new users and seasoned users to program.

#

Unity API is either really friendly, or a bit convoluted, and thus far, the scene management is a bit wonky.

austere jewel
#

Sadly that'd make it more difficult, because then you would have to parse the outcome into an int any time you wanted to perform any maths.
The API is certainly a bit fucky though, you would think you could use a SceneAsset to handle all this, but it's an editor-only thing

#

So you've got to use buildIndex (ints,) or by name (strings,) to get Scene structs (something you cannot construct without the API). It's certainly jank ๐Ÿ˜„

broken socket
# compact ether Good lord, how are you a mod lol

He has a website with helpful troubleshooting content for most common Unity misunderstandings. So like he said he tries to genuinely understand people's mindset facing such problems as you had.
No harm intended :)

static coyote
#

What is the best way to do networking these days?

broken socket
#

"Best" way is always related to context. Describe your project in #archived-networking , then maybe you'll get a satisfying answer

ebon obsidian
#

Is this a good place to talk about TextMeshProUG2D?

#

I tried my question in 2d-code and got crickets lol

#

I guess I'll try here

devout hare
#

You'll get the same crickets here. People who know most about 2d code are in that channel.

#

Just be patient, this is a slow time here because it's the middle of the night in US

ebon obsidian
#

this is really about how the text system works and weird rules about setting up fonts. Like the little bit I could find makes it seem like the font system in unity is a bit persnickity

kindred tusk
kindred tusk
#

Then you can just swap the material out as required.

ebon obsidian
kindred tusk
#

My guess is that that material doesn't support outlines

#
        /// <summary>
        /// Sets the thickness of the outline of the font. Setting this value will result in an instance of the material.
        /// </summary>
        public float outlineWidth
        {
            get
            {
                if (m_sharedMaterial == null) return m_outlineWidth;

                m_outlineWidth = m_sharedMaterial.GetFloat(ShaderUtilities.ID_OutlineWidth);
                return m_outlineWidth;
            }
            set { if (m_outlineWidth == value) return; SetOutlineThickness(value); m_havePropertiesChanged = true; m_outlineWidth = value; SetVerticesDirty(); }
        }
        protected float m_outlineWidth = 0.0f;
#

This is the source

#

But TMP developers are advised to use the mobile shaders which do not have outline support.

#

If so you fix it by assigning the correct shader to the newly created material/

cosmic tendon
#

Anyone have idea how to make the MathF.Sin to be added to Y transfom because it starts makes Y = 0

#

when i add the + Y to the amp it just made it go crazy

flint sage
#

Because it's a feedback loop

junior sorrel
#

Hello epic devs
I'm working on a mobile game(In PlayStore) but I want to test the leaderboard without actually uploading it to PlayStore instead I want to test it in my phone when I install it using the APK

The issue I'm going through is when I install the game on my phone using the APK the authentication to google play isn't working, so leaderboard won't work.
I am sure the leaderboard works because when I install the game from play store but won't work from installing it from the APK

How can I solve this problem?
Please tag me onReply