#archived-code-advanced

1 messages · Page 153 of 1

humble loom
#
private HashSet<Vector2Int> mineCoordinates = new HashSet<Vector2Int>();
while (mineCoordinates.Count < mineCount)
{
  var coordinate = new Vector2Int(Random.Next(0, width), Random.Next(0, height));
  mineCoordinates.Add(coordinate);
}
#

ayylmao

cursive horizon
#

rip

sand raven
#

do you mean something like:

vector2 pos;
do{
pos = (random vector2)
}
while(mineLocationsHashset.Add(pos))```
#

oofx3

humble loom
#

almost identical code that's a nice meme

#

since hashsets are already distinct, you just keep cramming random vectors into it until it's the right size

cursive horizon
#

wait, which part does it do?

#

alternately, you can use one of these dealies https://en.wikipedia.org/wiki/Linear_congruential_generator

A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation. The method represents one of the oldest and best-known pseudorandom number generator algorithms. The theory behind them is relatively easy to understand, and they are easily implemen...

sand raven
#

yeah heavily saturated is one thing that worries me but im testing the code yallve given me now

humble loom
#

an easy workaround is if your mineCount > cellCount / 2, then invert your coordinate assignment

#

the hashset will then remove mines at the given coordinates

#

so your hash set will never be > cellCount / 2

cursive horizon
#

you might be able to just evaluate it lazily

#

like only generate mines in the area revealed when they click

humble loom
#

you can't do that. minesweeper is deterministic

#

i think you're forgetting that you can flag mines

cursive horizon
#

yeah i have not played minesweeper in a very long time

#

i'll take your word for it

#

either way, this is 'map generation' so it should be ok if it takes a while

humble loom
#

the empty spaces will display numbers to show how many mines they're touching

cursive horizon
#

plenty of games have a 'please wait while we generate the map' bar

humble loom
#

i can tell you how minesweeper actually does it

cursive horizon
#

or you could be tricky about it and do it behind the scenes on the menu screen or whatever

sand raven
humble loom
#

they have a bunch of binary files and they just strip off zeroes and 1s and 1s are mines

#

ezpz

cursive horizon
humble loom
#

yeah

#

they're microscopic

cursive horizon
#

there ya go

humble loom
#

you figure one 100x100 level is litearlly only 10000 bits

cursive horizon
#

yeah, the clever part is that to generate one, you only need to do a coinflip X times

cursive horizon
#

just do x coinflips and you don't have to worry about overlap

humble loom
#

it's not that simple because you need to control for how many mines are in a level

sand raven
#

yeah, one strategic factor that the player has is knowing how many mines are actually on the board

#

it has to be exact

cursive horizon
#

does it need to be known ahead of map generation though? or can the map generate roughly a similar amount each time?

humble loom
#

so what i'd do is i'd save off binary files, each one being like XY dimensions, Z mines, and each one can store dozens of levels trivially, you just randomly pick a number and offset by bits_per_level * randomVal

cursive horizon
#

you're right though, that does make it trickier

#

so yeah, i think i agree

humble loom
#

this is how i handled realtime perlin noise

#

i would pre-generate noisemap textures and randomly select them and offset them in realtime

cursive horizon
#

'just do it ahead of time' is often the best optimization

humble loom
#

games are always a balance of speed and memory

#

if you have a speed problem, make it a memory problem

#

luckily modern computers have a shit ton of memory

sand raven
#

there is one more problem. My game features a "safety mode" which ensures the 3x3 tiles under your first click are NOT a mine, so you cant lose on the first click and have at least a 3x3 to start off with

#

i guess if i did it the way you say, i could just impliment some method where it finds a free 3x3 location in the binary files and starts you from there

humble loom
#

well the generation is easy

#

that safety mode you could just manipulate the map once it's loaded

#

like

#
if (ContainsMineIn3x3(selectedCoordinate))
{
  // reassign nearby mines to new empty slots
}
#

or better yet

#
List<Coordinate> adjacentMines = GetMinesInRange(coordinate, new Vector2Int(3, 3));
// move these mines somewhere else
cursive horizon
#

could you just pick a starting spot and block it out before you add any mines?

humble loom
#

i think the idea is that admiral wants the first click to be safe

cursive horizon
#

oh i see, no matter where they click it needs to be valid...it doesn't start with anywhere open

sand raven
#

right, thats why im currently doing mine generation on the first click

humble loom
#

i think it's probably better UX to have the first click be as close to responsive as all the others

#

think about it, worst case scenario you're only flipping 18 bits

cursive horizon
#

i would probably just have your first click be an explosion or something

#

and it 'clears' those tiles

humble loom
#

oh that's an idea

cursive horizon
#

so you don't have to deal with moving any mines and the player can feel lucky that they got a couple mines in their first click

humble loom
#

even simpler

cursive horizon
#

if they are playing with safe mode on, they probably wouldn't mind that it's a little rng

sand raven
#

im personally not a fan of that idea, as another reason im doing this is that Im a fan of "proffessional" minesweeper. Im trying to go for low times at certain board sizes

cursive horizon
#

well if you are playing the 'pro' mode you wouldn't have safe mode on right?

#

i guess maybe you would...its' not much of a competition if you can randomly die on the first click

sand raven
#

i mean i feel like most other mineseeper programs i see impliment some sort of mechanic so that you cant lose on your first click, so i feel like having a free 3x3 at the start is fair

humble loom
#

classic minesweeper definitely doesn't

cursive horizon
#

yeah it's doable, but you do have to move the mines somewhere so now you have that 'don't place on the same square' problem again

sand raven
#

right. I going to get to work and try to impliment some of these ideas yall have given me. Ive never worked with binary files so thats gonna be fun to read up about

#

thanks for the help guys

humble loom
#

well think about this

#

it's probably significantly faster if you just read the entire level as an integer

#

if you're going for turbo speed

#

000010101000010100101010
1001001010101010010010101
0001010100010101010100101

basically laid out like that

sand raven
#

yeah i can see how that would be extremely efficient

humble loom
#

you'd need to pack some metadata at the top though and just know what the first few bits "mean" to your program

#

like maybe 4 bits to specify width, 4 bits to specify height, etc

sand raven
#

yeah i can do that. Im also planning to add a function where players can make their own minesweeper board and share them with others, so that might be hands to know for implimenting that

humble loom
#

for sure. if you don't want to be super crazy you can simply make it a text file and set up a "grid" class that you can serialize/deserialize to/from

#

unity and c# play incredibly nice with JSON files

sand raven
#

right, ive got a lot to learn. im still pretty new with unity. before now i didnt even know vector2Int's were a thing. Ive really gotta read up more on all the diffent classes unity and C# have

humble loom
#
{
"mineLocations": {0, 0}, {9, 5}......
}
#

unity comes packaged with newtonsoft out of the box. it's a json serialization tool

#

you can set up a class to serialize TO json, so you can see what it looks like. hold on a moment i'll do a quick thing

sand raven
#

thanks. ive also haveant practiced saving stuff with unity. Actually i think the most ive dont with saving files using code was writing a text file back in my COMP3220 class

#

so this is going to be a great experiece

humble loom
#

JSON is your best friend when it comes to unity save data

#

are you familiar with a term called DTO?

#

it's more popular in web dev, but it stands for "data transfer object" basically it's a class you use specifically for moving data across application contexts

#

application puts data in, poops out a JSON file, reads data in, makes one of those objects

sand raven
#

gotcha, looking up info about that now

ebon cobalt
#

I think it's "there are rules "but I could be wrong, sorry for the ping. Have a great rest of the day and week

humble loom
#

OKAY

#

you still there apple?

sand raven
#

ok, after implimenting the while loop using a hashset for generating mines, converting a lot of my Vector2's to Vector2Ints, and cleaning up code, i can generate at 500x500 board with 45,000 mines in .002 seconds, which frankly is an incedibly improvement. With the same 500x500 board and 249,900 mines (100 less than the max) it froze and i stopped waiting after 5 mins

sand raven
humble loom
#

okay so check this out

#
[Serializable]
public class GridData
{
    private static string GridDataFolder => Path.Combine(Application.persistentDataPath, "GridData");

    [JsonProperty] public Vector2Int dimensions;
    [JsonProperty] public List<Vector2Int> mineLocations = new List<Vector2Int>();
    

    /// <summary>
    /// Loads a grid data JSON file into this object
    /// </summary>
    /// <param name="fileName"> The name of the data file </param>
    /// <returns> The newly created GridData object </returns>
    public static GridData Load(string fileName)
    {
        EnsureDirectory();
        string fullPath = Path.Combine(GridDataFolder, fileName);
        Debug.Assert(File.Exists(fullPath), $"File doesn't exist: {fullPath}");
        string json = File.ReadAllText(fullPath);
        return JsonUtility.FromJson<GridData>(json);
    }

    /// <summary>
    /// Saves current grid data into a JSON file
    /// </summary>
    /// <param name="fileName"> The name of the data file </param>
    public void Save(string fileName)
    {
        EnsureDirectory();
        string fullPath = Path.Combine(GridDataFolder, fileName);
        string json = JsonUtility.ToJson(this);
        File.WriteAllText(fullPath, json);
    }

    private static void EnsureDirectory()
    {
        if (!Directory.Exists(GridDataFolder))
        {
            Directory.CreateDirectory(GridDataFolder);
        }
    }
}
#

that's an example grid data DTO that i might make. pretty simple. just the data, a save method, and a load method

#

and the data file ends up looking like this

#
{"dimensions":{"x":100,"y":100},"mineLocations":[{"x":82,"y":33},{"x":20,"y":16},{"x":53,"y":88},{"x":76,"y":4},{"x":85,"y":74},{"x":69,"y":0},{"x":74,"y":43},{"x":94,"y":91},{"x":3,"y":4},{"x":18,"y":94},{"x":14,"y":33},{"x":64,"y":69},{"x":64,"y":47},{"x":43,"y":30},{"x":43,"y":56},{"x":35,"y":86},{"x":8,"y":53},{"x":81,"y":63},{"x":81,"y":79},{"x":51,"y":0},{"x":72,"y":47},{"x":20,"y":99},{"x":8,"y":9},{"x":93,"y":54},{"x":82,"y":59},{"x":4,"y":47},{"x":81,"y":27},{"x":57,"y":26},{"x":36,"y":52},{"x":82,"y":13},{"x":71,"y":35},{"x":53,"y":73},{"x":79,"y":15},{"x":68,"y":43},{"x":17,"y":4},{"x":31,"y":35},{"x":78,"y":83},{"x":70,"y":79},{"x":83,"y":28},{"x":60,"y":86},{"x":23,"y":51},{"x":28,"y":86},{"x":9,"y":84},{"x":56,"y":14},{"x":55,"y":72},{"x":1,"y":54},{"x":93,"y":64},{"x":34,"y":56},{"x":8,"y":86},{"x":88,"y":11},{"x":94,"y":60},{"x":45,"y":9},{"x":68,"y":92},{"x":60,"y":70},{"x":3,"y":46},{"x":41,"y":17},{"x":71,"y":70},{"x":44,"y":83},{"x":59,"y":63},{"x":85,"y":17},{"x":12,"y":48},{"x":58,"y":39},{"x":44,"y":89},{"x":1,"y":68},{"x":82,"y":42},{"x":42,"y":65},{"x":83,"y":20},{"x":59,"y":78},{"x":33,"y":25},{"x":10,"y":39},{"x":94,"y":21},{"x":71,"y":98},{"x":77,"y":10},{"x":85,"y":13},{"x":58,"y":10},{"x":0,"y":13},{"x":83,"y":26},{"x":39,"y":20},{"x":62,"y":94},{"x":82,"y":50},{"x":39,"y":42},{"x":89,"y":32},{"x":36,"y":66},{"x":62,"y":36},{"x":54,"y":51},{"x":30,"y":38},{"x":4,"y":73},{"x":18,"y":75},{"x":68,"y":65},{"x":46,"y":19},{"x":76,"y":38},{"x":4,"y":88},{"x":68,"y":13},{"x":24,"y":93},{"x":92,"y":81},{"x":65,"y":82},{"x":4,"y":28},{"x":35,"y":22},{"x":45,"y":24},{"x":16,"y":65}]}
sand raven
#

yooo this is dope, thisll be a great way for me to learn how to save to JSON

humble loom
#

indeedily

#

so when you want to load up a level you might have like an ACTUAL grid class that does something like

sand raven
#

im gonna play around with it. When it comes to the board editor i mentioned earlier, i also want users to be able to have their custom maps start with already flagged/revealed tiles

humble loom
#
GridData data = GridData.Load("level_1.dat");
Vector2Int grid = new Vector2Int(data.dimensions.x, data.dimensions.y);
foreach (Vector2Int coordinate in data.mineLocations)
{
  grid(coordinate.x, coordinate.y) = 1; // indicate a mine
}
#

oh ok

#

that would be trivial, you would just add lists for flagged/revealed tiles if you wanted

#

or you could change the format of the save file to store literally the entire grid, and each integer would represent a different state

sand raven
humble loom
#

yep

sand raven
humble loom
#

the whole idea of a DTO is the file knows its data, and it knows how to save and load itself

sand raven
#

Well thanks for writing that up for me man, im definitley going to be implimenting that

humble loom
#

it's a good idea to leave the business logic to other classes though

#

just treat these guys like little more than structs if that makes sense

#

np! i'm doing a lot of this stuff for work right now so it's in my brain

sand raven
#

right, i can understand that

gleaming thistle
humble loom
#

anyway i'm off to bed, good luck sir! you've taken your first step into a brave new world

#

just wait until you find out about adressables and asset references

#

btw the reason load is static and save is not is just because i like the semantics of being able to to myInstance.Save() and var myInstance = GridData.Load("someFile.dat")

#

and file suffixes don't matter, the code still knows it's json. i just use dat to signify that it's for game data

#

you might be better off saving to .json if you want to dump the files into a text editor like sublime or VS so you can manipulate the data manually

sand raven
humble loom
random dust
#

Maybe this changed with the latest version

wispy summit
#

When you're creating a state based menu system, how do you keep track of both the instantiated menu prefabs and the states?

#

Do you create a menubase type with a function that returns the state it's associated to?

#

(I feel like I just answered my own question) =_=

#

In any case, I'd love to know if there are other, more efficient ways to handle a state based menu system

compact ingot
tough tulip
misty crescent
#
Unable to resolve reference 'Microsoft.Extensions.DependencyInjection.Abstractions'. Is the assembly missing or incompatible with the current platform?```


Anybody know how to solve this?
compact ingot
misty crescent
#

Also, this is my Mac machine

compact ingot
#

it has to be one that is compatible with your build target

#

netcore stuff probably won't work in unity, depending on what version of unity you are using

misty crescent
#

you mean unity for mac?

#

so how do I get AWS to work with Unity on my mac?

#

This works on my windows machine

compact ingot
#

use the standard2.0 version if it is available

misty crescent
#

i am

compact ingot
#

the standard2.0 version of the AWS SDK

misty crescent
#

I am using the standard2.0 version

#

^ this one

#

Any thoughts?

#

do I neet .NET on my mac by any chance? looks like no because my game runs without it. But when I build it throws the error I linked above

compact ingot
#

and what version of Microsoft.Extensions.DependencyInjection.Abstractions?

misty crescent
#

Looks like...it's not there in my AwsAssemblies

compact ingot
misty crescent
#

But why? it's not there on my Windows machine too. Does my Windows machine implicity inject something?

compact ingot
#

on windows it is probably installed as part of windows or you installing visual studio and is discovered automatically

misty crescent
#

yup, sounds like you're right

#

any idea what I have to download on Mac now? Just this Microsoft.Extensions.DependencyInjection.Abstractions?

compact ingot
#

i usually download the nuget that contains it and extract the dll/version i need and copy that to the asset folder

misty crescent
#

How do I determine which version I need? That isn't mentioned in my stacktrace

compact ingot
#

the standard2.0 version

#

it has additional dependencies you may have to install

misty crescent
#

I have those I think

compact ingot
#

lets hope for the best

misty crescent
#

yeah, trying now. downloaded .NET 6.0

#

Could not find any project in /Users/myname/

when I try to dotnet add the package. Is it not some sort of global install?

compact ingot
#

yes, but unity doesn't care about those

#

unity wants to be treated special

misty crescent
compact ingot
#

thats fine, but once done, you have to make sure that you have indeed installed the netstandard2.0 version somewhere and you have to use the CLI to extract the DLL that you need... you can also do all this with visual studio or rider in the actual unity project and drag&drop the files as needed.

misty crescent
#

I have Rider installed

compact ingot
#

then just use rider's nuget client, install it, drag the dll to your assets and uninstall/delete the nuget again

#

maybe rider can even convince unity to keep & reference installed nugets.... i dont know

misty crescent
humble loom
random dust
#

I never liked it

#

Including DLL's like Newtonsoft is possible anyway so I'd rather just do that and use a newer version than use theirs

#

That said, why is it so hard to do that anyway? I'd assume it would be possible to add NuGet packages through the manager by now

compact ingot
wispy summit
#

Previously I had all the menus in the scene itself, they each had a component that helped identify them, with a field representing the state they coresponded to. When state changed, it would iterate through the whole thing making changes as necessary.

#

But it becomes complicated when those menus are loaded dynamically from prefabs.

#

I guess I could just poll the container object to register the components in the instantiated prefabs, and then continue using the old method.

humble loom
#

but yeah i like using new newtonsoft because you can serialize while maintaining SOLID principles. instead of having public members you can serialize properties

flint sage
#

Most serialization is yaml, they only do json for a few things

#

Most of those were around before serialize reference

humble loom
#

oh gotcha

#

i do know they designed scriptable objects to be trivially serialized to/from json which is very handy

violet fjord
#

hi guys, I don't suppose anyone is good at database stuff (using php atm)

#

not having much luck in the official c# discord is all.

drifting galleon
#

this is not a php discord

fresh salmon
#

If your issue is related to Unity, then please elaborate.

#

Else, you'll need another server

violet fjord
#

Might be easier to explain if I show the code I have (c# ofc)

#

IEnumerator Login(string username, string password)
    {
        WWWForm form = new WWWForm();
        form.AddField("loginUser", username);
        form.AddField("loginPass", password);


        using (UnityWebRequest www = UnityWebRequest.Get("http://localhost/Minigame1/Login.php"))
        {
            yield return www.Send();

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
            }
        }
    }

#

I was told that this isn't sending the form info (username/password) to my php script but I'm not sure why.

#

I'm using a Start method to run the Login method with the default test user credentials.

drifting galleon
#

you're only getting data. not sending any

violet fjord
#

Do you know how I could do that? 🙂

fresh salmon
#

Probably with UnityWebRequest.Post

violet fjord
#

Something along these lines?

fresh salmon
#

Looks good to me

violet fjord
#

hm, still doesn't seem to be working.

fresh salmon
#

Have you got any debugging measures in place server-side?

#

Like, dumping the contents of $_POST or whatever it's called

violet fjord
#

I just have it set up to tell me if there's anything in the username and password variables in my php script or not (there still isn't)

#

Is there anything that should be done alongside UnityWebRequest.Post?

fresh salmon
#

Apart from passing the form and yield return send it, nothing else

hearty garnet
#

Hello. I have an expensive function for figuring out where to spawn enemies that takes like 100ms to calculate. When I call it, game lags. But it is not a time critical function, I don't need instant results from it. I was wondering, how to code it so game won't lag

#

I tried Task.Run() but it wouldn't let me call Unity functions from inside a Task

sly grove
hearty garnet
#

Hmm I see.. So if it does like 1million for loops, I should WaitForSeconds(0.1) every 100 loops

#

For example... ?

sly grove
#

no you don't WaitForSeconds(0.1)

#

you just yield return null to wait a single frame

hearty garnet
#

gotcha thanks

#

and it does couple thousand iterations, not a million (hopefully) 😄

violet fjord
#

networking is straight up impossible man I literally just want to have a user login

#

been a good run, I give up lol

calm field
#

Hi, does anybody know, how i can see what destroyed a gameObject? At OnDestroy the callstack is gone and something is destroying my Player Object. I'm guessing that its one of the many assets i use in the project. but i need to know which function triggered the Destroy.

plucky laurel
#

huh one of the cases where callstack would not help

#

type GameObject.Destroy(), right click, find all references, and.. find it

calm field
# violet fjord been a good run, I give up lol

It shouldn't be that hard. To investigate if your bug is in unity or in the backend you should try if you backend works without unity. To do this u can manually send a POST request via javascript(browser) or a tool like Postman (or from the console with wget or curl). When you succede to login from there u know that your backend is working.

calm field
plucky laurel
#

yep

#

thats your best chance

humble loom
#

I've got a question about customizing built in editor windows

#

i saw some package that had a customized unity console. and it had added tabs besides clear/collapse etc. they added dropdowns for common filters

#

did they just remake the window entirely? or is there a way to just add to it

alpine nebula
#

UP !

alpine nebula
#

No idea ?

mint sleet
#

Hey! Is it a good practice to split project into different projects while working on SAM

#

For instance I have a SAM infrastructure for API Gateway and its Lambda functions. (This is one project)

#

And "ElasticSearch" integration is another Lambda project.

#

Thanks

cedar ledge
tough tulip
humble loom
#

Why does unity package newtonsoft out of the box then?

tough tulip
#

unity json still works when you remove the newtonsoft :)

#

Unity Json works on the principal of how unity internally serializes the data. That's the reason they don't support dictionaries because they don't serialize it. Even the earliest versions of newtonsoft json in c# supported dicts

tough tulip
tough tulip
small badge
# humble loom Why does unity package newtonsoft out of the box then?

It's a little convoluted; as I understand it Unity's internal json serializer (that is, com.unity.modules.jsonserialize) is not built on newtonsoft json and does not require it. However, some other optional unity packages are built on top of newtonsoft json, which is why they distribute a standardised version of it as its own package com.unity.nuget.newtonsoft-json?

wispy summit
#

What's the workaround for having 'static' derived classes from a generic class? (I'm creating catalogue classes, so i dont need multiple instances anyway. But since the logic is the same, I was hoping to create a generic class as the base)

alpine nebula
#

calloc > malloc :3

wispy summit
alpine nebula
#

it's just joke for malloc boy but not for you sorry ..

wispy summit
#

oh whoops. didn't notice the previous participants. my bad

alpine nebula
#

ahah np

calm field
wispy summit
#

you can do a full project replace from Destroy( to Debug.Log($"{GetType()} is destroying an object"); Destroy(

#

or something along the lines of that

spring echo
#
[SerializeField] private Transform _list;
    public override void OnServerAddPlayer(NetworkConnection conn)
    {
        GameObject gameObject = Instantiate((GameObject)Resources.Load("PlayerLobby"), _list);
        NetworkServer.AddPlayerForConnection(conn,gameObject);
        CSteamID steamId = SteamMatchmaking.GetLobbyMemberByIndex(SteamLobby.LobbyId, numPlayers - 1);
        var playerInfoDisplay = conn.identity.GetComponent<PlayerInfoDisplay>();
        playerInfoDisplay.SetSteamId(steamId.m_SteamID);
        base.OnServerAddPlayer(conn);
    }
    public override void OnClientConnect(NetworkConnection conn)
    {
        if (!clientLoadedScene)
        {
            if (!NetworkClient.ready)
            {
                NetworkClient.Ready();
                NetworkClient.AddPlayer();
            }
        }
        base.OnClientConnect(conn);
    }
tough tulip
remote oar
#

has anyone ever seen this error? I have no idea where the actual error comes from =/

#

Its a server build

#

It's crashing on Resources.Load for some reason. It has worked before, so im not sure..

tough tulip
#

this could also happen if your project files get corrupt. so try a simple rebuild aswell

remote oar
#

yeah it was some weird unity bug

#

when i called the load function somewhere else it suddenly started working again

mental rapids
#

Hello hello, i'm having some issue with a tool that i am making
i loop over all the vars of a component, and if there is a unity event, i save it
The problems are on ui element, on scrollbar for exemple
They have events, but its "scroll event", and i can't cast it to unity event
Does anybody know how to do that and f its possible ?

#

the scroll event inherit from unity event

plucky laurel
#

no

#

it inherits from UnityEvent<T>

#

the common base is UnityEventBase

lucid yoke
#

I want to make an exercise mobile game. I want to track the amount of steps taken by the player irl. I can't find a way to access the native api. Can anyone suggest an approach or something to read up on?

sly grove
lucid yoke
sly grove
#

Native plugins

mental rapids
mental rapids
plucky laurel
#

you cant convert a type that has no relation to another type

#

you can "convert" by doing actual conversion, theoretically but you cant cast it

mental rapids
#

Fuck.. :/
In editor window, i can get the value of the unityevent parameter like that :

#

but with a unityeventbase, nothing return, do you know how to get the parameter of a unityeventbase, if its possible, i can't find anything on google

plucky laurel
#

look into the sources

lucid yoke
mental rapids
plucky laurel
#

yes ui package sources

#

on github or use decompiler

#

use them to find whatever you need

mental rapids
#

oof, never did that

plucky laurel
#

going blind only gets you that far

mental rapids
#

okay okay, i'll try to do what you say !

high mirage
#

how do i load a font in runtime? i've tried putting it in the resources folder and using Resources.Load() but that didn't work, couldn't find a solution, any help?

labelStyle.font = Resources.Load("VCR_OSD_MONO.ttf") as Font; // labelStyle is a GUIStyle```
sly grove
high mirage
#

that was it

#

can't believe I wasted like 30 minutes

sly grove
#

Oops

high mirage
#

ffs

#

thanks praetor

#

appreciate it, man

red osprey
#

So... for async/await. How do we know if the thread that wakes up after an await is the game thread?

fresh salmon
#

If what started the async tasks is the game thread, and that there are no .ConfigureAwait(false) on all top-level await calls, then you're on the game thread

red osprey
#

Cool. Thanks!

tough tulip
pastel moth
#

Hey, I have the following code that looks for enemies... however, my enemies now want to "cast spells".. how can I check for 'current enemy' and omit it from the list/make sure it doesn't cast on itself? ```void TargetEnemy()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
float shortestDistance = Mathf.Infinity;
GameObject nearestEnemy = null;
foreach (GameObject enemy in enemies)
{
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
if (distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}

    if (nearestEnemy != null && shortestDistance <= range)
    {
        target = nearestEnemy.transform;
        targetEnemy = nearestEnemy.GetComponent<Enemy>();
    } else
    {
        target = null;
    }
}```
tough tulip
pastel moth
tough tulip
pastel moth
#

I changed this part of the code but it just won't "cast" anything if (nearestEnemy != null && shortestDistance <= range && !this.gameObject) { target = nearestEnemy.transform; targetEnemy = nearestEnemy.GetComponent<Enemy>(); } else { target = null; }

#

Brief; I have a tower defense game and my enemies are going to 'buff' enemies around it

#

I just don't want it to buff itself when it's a "single" cast spell

tough tulip
pastel moth
# tough tulip It's a very basic mistake. There's nothing advanced about this code no offense. ...

No problem; the other chats were busy so I didn't want to mix/get lost in it all.. I'm not sure where to put that check exactly... ```void TargetEnemy()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
float shortestDistance = Mathf.Infinity;
GameObject nearestEnemy = null;
foreach (GameObject enemy in enemies)
{
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
if (enemy!=this)
if (distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}

    if (nearestEnemy != null && shortestDistance <= range)
    {
        target = nearestEnemy.transform;
        targetEnemy = nearestEnemy.GetComponent<Enemy>();
    } else
    {
        target = null;
    }
}```
tough tulip
#

in Enemy?

pastel moth
pastel moth
tough tulip
#

then you need reference to Enemy

#

I assumed your function also resided in Enemy script

pastel moth
#

I do reference it..?

#

private Enemy enemy;?

#

Just to mention... Only enemies that can cast will have this script attached

pastel moth
#

For anyone wondering.. the fix is adding this after the foreach loop - if (go == gameObject) continue;

#

go = your GameObject refernce foreach (GameObject go in enemies)

wind wadi
#

I just learned about the ~ feature but don't know what it exactly does, can someone explain?

wind wadi
#

Alright thanks! I just didn't even know it was a feature in .NET

orchid marsh
orchid marsh
sly grove
orchid marsh
#

Haha, alright.

sly grove
#

The finalize method might be called on a finalizable object only after an indefinite delay, if at all

#

It's also deprecated

austere jewel
#

I would presume that's the same caveat in C#, no?

orchid marsh
#

Well.. GC languages are already special (or the other way around).. thankfully, not all are wearing the same uniform and carry the same suite case

sly grove
#

Maybe? You're meant to use the Disposable interface if you actually have resources that need cleaning up.

#

WHich I guess is the same in C# as well

devout grail
#

I want to manipulate an object's vertices during runtime.

How expensive is this? (For the CPU)

#

Essentially i want to make something like blender's bend functionality.

red osprey
red osprey
#

But it's certainly doable in a realtime sense.

#

If you're talking about a million triangle mesh... then maaaaaaaybe reconsider lol.

devout grail
#

You mean i can modify updated vertices with a shader?

red osprey
#

You can modify any vertex with a shader, yes.

devout grail
#

oh my

#

didn't know that

red osprey
#

In multiple ways... in the material, in a compute shader, whatever.

#

Typical method is the vertex shader though.

#

Like there was one game I was working on... this was never implemented, but they had hundreds of locker doors. I just uploaded a float array with a bunch of 0->1 values. 1 was open, 0 was closed, some decimal was that percentage level of open.

#

The actual vertices were rotated in a vertex shader. Easy peasy. Very fast.

devout grail
#

Ok 😮

#

I'm assuming normals are also recalculated

red osprey
#

Well "this was never implemented" it was implemented by not merged lol

#

Uhhhh

#

IIRC you need to calculate them in the vertex shader

#

They will then be interpolated based on whether the edge is smooth or hard.

devout grail
#

But i suppose i better start learning how to write shaders and such.

#

thanks for the info

somber tendon
#

It depends on the requierement of course, if the mesh will be always changing, and you dont need to interact with the changed mesh, then using shader will be more suitable, but if it's only change one time, then using script would be just fine

devout grail
#

the mesh will be always changing

#

but the required data for the bending is minimal

#

And i hope my barely sufficient linear algebra to pass my exam will be useful here

#

lol

#

Just another question out of curiosity:
When you have a characted animated with a skeleton, does that calculation also happen on the GPU?

red osprey
#

GPU skinning is done in a vertex shader (and, fun fact, blendshapes are done in a compute shader). That said, I don't know exactly everything that's done on the GPU.

#

But it's at least partially GPU.

devout grail
#

Oh wow, i thought gpu's only did much more basic stuff.

eternal parrot
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;

public class MoveToGoal : Agent
{
 
    [SerializeField] public Transform targetTransform;
    public override void CollectObservations(VectorSensor sensor)
    {
        sensor.AddObservation(transform.position);
        sensor.AddObservation(targetTransform.position);
    }

    public override void OnActionReceived(ActionBuffers actions)
    {
        float moveX = actions.ContinuousActions[0];
        float moveY = actions.ContinuousActions[1];
        float moveSpeed = 1f;

        transform.position += new Vector3(moveX, moveY, 0) * Time.deltaTime * moveSpeed;
    }
}

error

IndexOutOfRangeException: Index was outside the bounds of the array.
Heuristic method called but not implemented. Returning placeholder actions.
UnityEngine.Debug:LogWarning (object)
#

why is this error occuring

sly grove
regal olive
#

im trying to run a basic ar scene with arcore but the screen is black and get this on logcat

high mirage
#

how do i change the color of a GUI slider? changing GUI.color doesn't do anything

tough tulip
# sly grove Something that isn't guaranteed to be called 😦

From what I know finalize in Java is not called when the application quits, because the memory occupied by the complete JVM is deallocated at one swoop not by garbage collector. But still you can force finalize for graceful shutdowns. I wasn't aware of deprecation and I haven't used Java in past 7-8 years aswell. But I reckon it should still work

next grove
#

Is it possible to extend unitys built in physics material with additional properties somehow?

glass wagon
untold moth
#

Might need to write a custom inspector for it though.

#
    public class CustomPMat : PhysicMaterial
    {
        public float radioactivity;
    }
next grove
next grove
next grove
#

The second one might work, thanks
The first i tried but it's only for scriptable objects

untold moth
#

Actually, I see the problem now. PhysicMaterial is just a wrapper for a c++ side object, so I think any custom data would be lost if you try to access it via collider.physicMaterial(or whatever the property name is) even if you manage to serialize the type.

#

Maybe not.🤔 Requires testing

glass wagon
#

There are huge problems with changing the material properties that are exposed, during gameplay. It's a schmozzle. Best way is to use custom written controllers that sense what's going on and act as you need. If it's a car/wheel, you're going to need do it every physics step. Instead of using a Dictionary, use an array as a Look Up Table, and a Switch statement with enums. Or a master controller that takes your structs as its state objects to do the calculations as overrides. Presuming this is for drifting and sliding around, you're going to have a LOT of fun. This is not a solved problem.

glass wagon
#

And tap into your inner Raikkonen

next grove
#

The dictionary method has been working fine in our last games, i was just looking for cleaner way to have all the relevant surface values in one place

remote oar
#

does anyone know why forces wont be added when 1 force is coming from the fixed update (movement) and 1 force isn't

#

for some reason it counters eachother

#

and the second force will be less than when you are standing still

plucky laurel
#

a wrapper should suffice

next grove
#

Not sure how a wrapper class would accomplish what i'm trying to do, but i might be missing something since i've never used wrappers
I was just looking for a way to have physics materials in unity store additional values like tyre friction modifiers instead of having them somewhere else separately

compact ingot
untold moth
#

That's what I suggested earlier. The issue was we were not sure how to serialize instances into assets.

compact ingot
#

ah, right

untold moth
#

Since PhysicsMaterial inherits from Object. I don't know if the last suggestion worked for them or not..?🤷‍♂️

compact ingot
#

the dictionary is probably a fine approach... not everything has to be handled via language features

#

and cleanliness is just a matter of wrapping it neatly and hiding all ugliness behind a pretty interface

next grove
#
public class TestPM : PhysicMaterial {
    public float test;
    [MenuItem("GameObject/Create Material")]
    static void CreateMaterial() {
        TestPM material = new TestPM();
        AssetDatabase.CreateAsset(material, "Assets/TestPM.physicMaterial");
        Debug.Log(AssetDatabase.GetAssetPath(material));
    }
}

This works for creating the asset, a custom inspector also works, but it seems like unity only treats it as the TestPM type until the next script compilation after that it just shows the default physics material inspector

untold moth
next grove
#

Looks like it's an issue with the asset creation, both```cs
AssetDatabase.CreateAsset(new TestPM(), "Assets/TestPM.physicMaterial");

```cs
AssetDatabase.CreateAsset(new PhysicMaterial(), "Assets/TestPM2.physicMaterial");
```create the exact same file.
untold moth
#

Did you try using a different extension?

#

like .customPhysicMaterial or something

onyx blade
#

why not create a file with the type you are looking for, so you know for sure its the right extension?

#

as in, create in unity. not via code

next grove
mental rapids
#

Hello
I Have a class B, wich inerehit from A, and i need to cast B to A, so i did this :
B newB = new B();
A instanceA = (A)newB;
The problem is that the var "instanceA" still remember that he was inehriting from B, anyone know how to "kill" the link ?

small badge
#

You can't do this, or the previous thing you posted. An instance of B is always an instance of B, a SliderEvent is always a SliderEvent; casts are just different ways of looking at the same object.

mental rapids
#

yeah, it was just an easiest way to explain the thing^^

#

okay, thanks for your answer dude !

radiant geyser
#

Yo so I’m trying to implement procedural animation in my game and this is what I have so far:

#

The problem is that the legs just slide along the floor to the new target, when I want it to kind of step to it

mental rapids
radiant geyser
#

So what would be the best way to get a stepping motion? I was thinking to have it interpolate a point between the target and current position then go up a bit and have that as the first target, then it goes to the final target from there

#

But it doesn’t seem like a great solution so I was wondering if there’s a better way

mental rapids
#

do you have a reference of what you want ?

eternal parrot
mental rapids
radiant geyser
humble leaf
radiant geyser
#

So in the video it doesn’t really go over how to get the stepping motion so that’s the only part idk how to do

mental rapids
#

when the target is far enough, you are just doing like "legposition = targetposition" ?

radiant geyser
#

Pretty much

#

I use Lerp to make it smooth but yeah

#

So do you have any ideas

mental rapids
#

show me how you are doing the lerp

radiant geyser
#

leg.position = Vector3.Lerp(leg.position, hit.point, 30f * Time.deltaTime);

mental rapids
#

one case can be:
when you can lerp your leg position, of the first frame, the position of the target as vector3 and get the distance between leg and target
then, at each frame so, you get the distance between the current leg pos and the saved vector3
then you can do compare the current distance to the first distance, and lerp the ypos of the leg to the target y pos

radiant geyser
#

I tried to implement it and its a bit glitchy and doesnt work great

mental rapids
#

not for the x and z pos, only the y pos

radiant geyser
#

what

#

but the y pos for the leg and the target will always be 0

#

only way to raise it is by adding a point in between

mental rapids
#

normally bu doing that, you not have strange glitch

radiant geyser
#

hmm i think i have something similar but the problem is lerping it back to the ground then

#

like i have it split into 2 lerps then

mental rapids
#

yeah, split it in two lerp

#

its normal that you have strange thing, if you have two lerp, and that your lerpvalue is Time.deltaTime

#

if you have two lerp, you will have two ease

radiant geyser
#

idk its just causing some timing issues

#

having 2 lerps

#

trying to work on it now

mental rapids
#

normally of its done correctly, it will work

radiant geyser
#

yeah ik, its just like i said, its not a great solution

#

because I need to fine tune each of the values and they will only work for this specific use case

#

like if I adjust the spiders leg size or speed etc, the values wont work

#
leg.position = Vector3.Lerp(leg.position, leg.position + new Vector3(0, 0, hit.point.z), 30f * Time.deltaTime);
        leg.position = Vector3.Lerp(leg.position, leg.position + new Vector3(0, 0.01f, 0), 30f * Time.deltaTime);

        yield return new WaitForSeconds(0.1f);

        leg.position = Vector3.Lerp(leg.position, leg.position - new Vector3(0, 0.01f, 0), 30f * Time.deltaTime);
#

Is this what you meant?

mental rapids
#

not really

radiant geyser
#

then what

mental rapids
#

wait, doing a test

radiant geyser
#
leg.position = Vector3.Lerp(leg.position, hit.point + new Vector3(0, 0.1f, 0), 30f * Time.deltaTime);

        yield return new WaitForSeconds(0.1f);

        leg.position = Vector3.Lerp(leg.position, hit.point - new Vector3(0, 0.1f, 0), 30f * Time.deltaTime);
#

doing this now, seems to work okay

hearty garnet
#

I was wondering something. How would you make it so that certain objects are only visible at the edges of screen.

Think of it like this. Imagine you have a big rectangle at the center of your monitor. Instead of it showing something else like a window, i want it to show what the main camera would show, except typeof enemy.

high mirage
#

how do i add faint/ghost text to a GUI text field? this is just changing the text and color but i have no idea how to actually do it

warm adder
#

Hya. I'm implementing the new Input SYstem and I've hit a snag. When using a 1D axis, I need to know What action is pressed on that axis, the positive or the negative. So far though I've only been able to get the InputControl, which gives me the direct keycode. How do I get wheter or not its the Positive / Negative action?\

#

I am really enjoying using the new Input System btw, way better then the old. But, it is hard to find stuff, not very well documented so far

high mirage
warm adder
#

yeah thats the whole crux, there's so much to read and so little documentation

high mirage
#

lemme get a link

fresh salmon
#

Normally a 1d input should just come up as a float, which you can compare to 0 to see if it's negative or positive

high mirage
#

one of her many new input system tutorials

warm adder
warm adder
#

Hmmm, reading the float Does identify the keypress. But it doesnt identify the Key Up (canceled action), since the value then is 0

fresh salmon
#

Ask the question directly, if someone can help, they will. However I sense some red flags in that message:

  • You're new to Unity programming, but posting in #archived-code-advanced,
  • You're placing deadlines ("it wouldn't take a day if you're good").

Do you actually want help, or do you just need someone to program it for you? If it's the latter, then I'm afraid it's not the right place to ask this. Collaboration requests go on the Forums instead.

#

Message deleted, I guess it indeed was the latter :))))

short junco
#

Guys how can I do world scrolling with vuforia can you give any kind of referance or advice to me ?

regal olive
#

(im going to take a gander and put this in this channel but if it doesn't belong here please do ping me @regal olive and ill remove it and move it to #archived-code-general or wherever it belongs)
so i have this algo here

for (int i = 0; i < onsets.Count-1; i++){
                float rangemult = max / range; 
            
                for (float i2 = 1f; i2 < range+1; i2++){
                    if (onsets[i] >= rangemult*(i2-1f) && onsets[i] <=           rangemult*i2){
                        sorted.Add(((rangemult*i2)*2f)*10f);
                    }
                }
            }

onsets is a huge array containing numbers always below 1
so things like 0.3278319782, 0.5684309584, 0.217382167, 0.6895786578 (they never go negative by the way)

range is 10
sorted is an empty list

and max is the highest value in onsets

basically it converts all those decimal numbers into whole numbers (or what i call reasonable numbers since sometimes it will output shorter decimals as apposed to long winded decimals but don't worry about that)
so if we had max as 0.5
then all 0.5's in the onset array would become 10
0.2 would become 4
0.4 would become 8
and so forth...

how could i get the highest value from sorted without needing to execute the algorithm - is it even possible?

merry robin
#

@regal olive sounds like an interesting homework question.

regal olive
#

woah do you mean to say you think my code validates as homework given by a teacher? - dayum that makes me smile 🙂

merry robin
#

nothing so flattering was intended 😛

#

if you're looking for an 'easy' way to find maximums

#

System.Linq has a lot of useful stuff

regal olive
#

omg i completely forgot about linq - is it much faster than doing a for loop twice though? - from what i've heard it can be slower depending on the task - unless i've been misinformed :p

merry robin
#

depends wildly on the task and datatypes and even target processor

#

if you're going for pure speed, don't use dynamically sized lists, use fixed length arrays

regal olive
#

wait theres noticable difference between lists and arrays - i've been tricked this whole time lol! - cheers dude (not only for the flattery xd) i'll give linq a try and update if i stumble on any more brick walls :)

small badge
brave jasper
#

yo while at the subject of axis maybe you guys can help

#

this is what my X axis returns when i move it left to right

fresh salmon
#

Question migrated from #💻┃code-beginner. They're using a steering wheel and the legacy Unity Input Manager

brave jasper
#

yeah yeah

fresh salmon
#

The axis does not report the value right.

#

That's the information you need to include in your original message.

brave jasper
#

i wanna add it reports it right outside of unity in other software

#

update, if i disconnect the device and hold it a bit to the left while connecting it again i can kinda offset it

#

but the issue is still that the wheel is say 135 degrees and the axis spans only on 90

#

pedals also work fine

void canyon
#

Hey, does someone here understands a lot about addressables? I'm trying to build the bundles to upload to my server, but the only thing that gets built is the remote catalogue, none of the groups are built (and yes, the build path for both the catalogue and the groups are set to "remoteBuildPath")

quartz stratus
#

Is your problem that the Addressables aren't being built when you make a build from the editor?

void canyon
#

Yes

quartz stratus
#
AddressableAssetSettings.CleanPlayerContent​();

AddressableAssetSettings​.​BuildPlayerContent​();

I use an editor script to run these two lines before every build so Addressables are included. I'm not sure if this will solve your problem with your use-case and your server but it's maybe worth a shot.

void canyon
#

Okay, let me try

quartz stratus
#

Just for context, here's my full editor script. Apologies for the code dump.

using​ ​UnityEditor​; 
 ​using​ ​UnityEditor​.​AddressableAssets​.​Settings​; 
  
 ​public​ ​static​ ​class​ ​AddressableBuildService 
 ​{
  
 ​    ​private​ ​static​ ​void​ ​CleanAndBuildAddressables​() 
 ​    { 
 ​        ​AddressableAssetSettings​.​CleanPlayerContent​(); 
 ​        ​AddressableAssetSettings​.​BuildPlayerContent​(); 
 ​    } 
  
 ​    ​//​ Note: this will only prompt building with Addressables if the user builds from the Build Menu. 
 ​    ​//​ If we build using scripts or from the CL in the future, this reminder will not appear (BuildPlayerHandler is only called from the GUI). 
 ​    [​InitializeOnLoadMethod​] 
 ​    ​private​ ​static​ ​void​ ​Initialize​() 
 ​    {
 ​             
 ​        ​BuildPlayerWindow​.​RegisterBuildPlayerHandler​(​BuildPlayerHandler​); 
 ​    } 
  
 ​    ​private​ ​static​ ​void​ ​BuildPlayerHandler​(​BuildPlayerOptions​ ​options​) 
 ​    { 
 ​        ​if​ (​EditorUtility​.​DisplayDialog​(​"​Build with Addressables​"​, ​"​Clean and Build Addressables before export?​"​, ​"​Build with Addressables​"​, ​"​Skip​"​)) 
 ​            ​CleanAndBuildAddressables​(); 
 ​         
 ​        ​BuildPlayerWindow​.​DefaultBuildMethods​.​BuildPlayer​(​options​); 
 ​    } 
 ​}
brave jasper
#

NICE 😄

#

color

quartz stratus
#

thanks for the tip!!

brave jasper
#

np bro

void canyon
#

Oh well, it did't work

#

Only the catalogue got built, again

brave jasper
#

okay anyone familiar with writing custom HID for a controller or something along those lines ?

void canyon
# void canyon Hey, does someone here understands a lot about addressables? I'm trying to build...

God
Dammit
I can't believe I just lost 6 hours of my life on this
So, in the "Content Packing & Loading" Schema there's this option called "Include in build" which I thought meant the bundle would be included in the actual application build and so I had deselected it. But it seems that disabling it means that the bundle won't be added into the ASSET BUNDLES build, not the application build!

unreal lichen
#

help, anyone here familiar with unity 2d tilemap extras, speciallyu about prefab brush?

i used prefab brush on on my script, which use UnityEditor.Tilemaps, to auto generate a tile prefabs. i want to build the game then i encounteer error about UnityEditor, which make me realize this function cna only be run on unity editor(?) that's why when i run the game after using #if UNITY_EDITOR, the prefab brush wont be run, meaning no tile generated.

is there anyway for me to keep using the prefabBrush on the game buil?

gilded prism
#

Searching online I can't find anything on urp api for Light2D scripting besides something which seems out of date and says you just need Light2D which isn't working for me.

#
Light2D light2d;
void Start() {
    light2d = gameObject.GetComponent<Light2D>();
}
orchid marsh
#

Perhaps explain what're you looking for in particular; relative to URP.

mental rapids
#

at the end, you will have a vector two, if the x is between 0 and 1, the pivot point is on the screen, else its outside (but object can still be visible if it is large)

unkempt nova
#

Hey, sorry if this is in the wrong area, feels advanced to me. I'm profiling a game, it works fine on PC 100+ FPS but getting around 1 FPS on mobile. Phone is able to play COD Mobile no issues, so I'm profiling thinking we've screwed something up and seeing this. I can't make heads or tails of what I'm looking at, it seems to be internal stuff? Any advice would be appreciated

livid kraken
#

This seems to be compilation stuff happening in the editor

unkempt nova
#

That's what I was thinking, but it's in play mode. I don't get it

livid kraken
#

Are you profilling the build from the phone?

unkempt nova
#

No

#

Just in editor

livid kraken
#

Well you need to connect the profiller to the phone running a dev build

#

That way you can see what is going on

unkempt nova
#

Fair point. That sounds like a pain. Thanks though

novel wing
unkempt nova
#

Cool. Time to start researching how to do it haha. Thanks

livid kraken
#

Profilling mobile in the editor on a pc aint worth jack if you ask me

unkempt nova
#

I'm just at a loss, joined this project late to port to mobile, and running into this. Dunno where to begin

#

Profiling seems the obvious start

livid kraken
#

Yeah. You just have to profile the right thing

#

And that thing is the dev build running on the actuall device

flint sage
#

Agreed, also figure out what is taking long, CPU or GPU?

#

From there you can start using mroe specialized tools

unkempt nova
#

Yep, working on it now. Doesn't seem too bad at all from what I'm reading. Mostly just worried that it'll be stable with profiler+game already running at ~1 FPS

livid kraken
#

The profiler can run as a independat process to reduce the editor overhead

unkempt nova
#

Yeah, I'm talking about the phone itself

#

Figure it adds to the load there

flint sage
#

It's probably fine

livid kraken
#

Its gonna be fine

unkempt nova
#

Good news. Thanks

livid kraken
#

Ive never seen a case with such a huge diff in perf. Report back with what you find Im interested haha

flint sage
#

I'd expect it's some graphics thing that's just badly supported on mobile

unkempt nova
#

Oh yeah, build profile is dead easy and worked straight away

flint sage
#

URP with multiple stacked cameras?

#

Yeah that's expensive

#

What else is in that stack?

livid kraken
#

Yeah expand that execute render pass

#

Do you have custom render passes ?

unkempt nova
#

Ah, I killed it, trying a new build without deep profiling

#

I think we have custom render passes, not sure.

#

I'm told "if they mean Post processing and SSAO then yes, we have those" I don't feel like those are custom though. Building with deep profile again now, regular profile didn't seem to give me any info

flint sage
#

Right, step one is disable post processing and ssao

untold moth
#

Should have a look at the GPU profiler too

flint sage
#

You'll need mobile specific postprocessing if you want those

#

Best to leave it out for now to figure out if you even have the capacity

unkempt nova
#

Sounds like a good lead

#

@flint sage @livid kraken @untold moth Looks like simply disabling all the post processing sorted it. Still slightly low FPS, but definitely playable now. In hindsight, I should have thought to check it out, but this is looking at least 20x better. Thank you very much

flint sage
#

What phone are you running on?

unkempt nova
#

Samsung Galaxy A50

flint sage
#

Mid range specs with a relatively large screen will kill performance with postprocessing

unkempt nova
#

Makes sense. Wasn't sure where on the spectrum it was. Felt mid range

flint sage
#

You can't just compare apple vs android like that very well either fwiw

livid kraken
#

Fullscreen pp kills the mobile. Especially on tile based renderers

unkempt nova
#

Getting this now, with deep profiling build on phone. Is that just profiling crap?

#

This is with all post processing disabled

fresh salmon
#

Seems like it yeah, it's creating some class instances in there

untold moth
#

Always profile without deep profiler first. There's usually more than enough info.

unkempt nova
#

Last regular profile didn't seem to tell me anything, so I skipped it. Think I should try another regular profile now and post?

#

Meh, gonna do it anyway

untold moth
#

Meaning there was no performance issues..?

unkempt nova
#

Same info I think, just less subdivisions

#

Trying now

flint sage
#

Deep profiling is quite expensive

unkempt nova
#

Yeah

flint sage
#

I can imagine that in a rendering pipeline it builds up really quick

untold moth
#

In the last screenshot you shared there's still post processing and deep profiling enabled, so we can't say what's wrong when you disable both

unkempt nova
#

Yeah, didn't post without it. Should be ready in a sec

#

Mobile build takes like 8-9 minutes each T.T

flint sage
#

Lucky you

unkempt nova
#

lol

#

This is what I'm getting without deep profiling, based on what SPR2 said about Semaphores, looks like I'm just hitting a GPU bottleneck here?

untold moth
#

Try looking at the gpu profiler module first. If it works on your device.

unkempt nova
#

Digging a bit deeper

untold moth
#

If not, either find native gpu profiling tools or just look at your project and optimize anything that could be have on the gpu.

unkempt nova
#

GPU just says no frame data available. Sounds like not

flint sage
#

Mihgt not be enabled in the build

unkempt nova
#

In the build? How do I check that? These are my current build settings

flint sage
untold moth
# unkempt nova

Well, then you can only guess and test. Things to check:
-heavy non mobile friendly shaders
-a lot of geometry to process(vertex/triangle count)

unkempt nova
#

Yeah, makes sense

flint sage
#

There's a bunch of platform specific profilers that you can use

unkempt nova
#

Know of one, so I can get that ball rolling?

#

Before I just google "Unity platform specific profilers"

flint sage
#

ARM mobile studio, qualcomm snapdragon profiler

#

Google also has some tools iirc

unkempt nova
#

Awesome. Thanks

flint sage
#

They tend to not be as user friednly as Unity's tools though

unkempt nova
#

Ah. Boo

untold moth
#

I think you need to use the one that is compatible with your device chipset

#

*from the producer of the chipset

flint sage
#

They're often the best but there's also more general purpose ones

#

You can also just switch to opengl es 3 and use the unity profiler

unkempt nova
#

Ah, makes sense. I think I'll try poking around for player settings and stuff before I open that can of worms

untold moth
#

I never had any luck with these tools for some reason. Maybe my device is just poopoo 😅

unkempt nova
flint sage
#

I'd remove it just in case

flint sage
unkempt nova
#

Ok, will try that out. Triggered a reimport looks like. Think this is gonna be a while lol

untold moth
flint sage
#

That shouldn't do that much

untold moth
#

Perhaps. It did help me in one of my projects a lot and I'm using it ever since on mobile.

unkempt nova
#

Ok, will try that out later. This is probably gonna be 20 minutes

#

Any suggestions are helpful

#

Think swapping color space triggers another reimport too

#

@flint sage Btw, weren't you just starting out with Unity a couple years ago from another engine I thought? Or was that someone else

untold moth
flint sage
#

With not much prior gamedev experience

unkempt nova
#

Ah, ok. Must be someone else

flint sage
#

Back when the Unity IRC was still thriving

unkempt nova
sage radish
#

@unkempt nova A quick way to check if you're CPU or GPU bound is to reduce the rendering resolution. If you see a gain in performance, then the GPU is the bottleneck.

unkempt nova
#

Ooh, great call. How do I do that?

#

In build settings right?

sage radish
#

I'm more familiar with VR, where it's pretty easy to change the render scale.

#

But I guess you should be able to use Screen.SetResolution

unkempt nova
#

Ah, ok. Thanks 😄

sage radish
#

Are you using URP?

unkempt nova
#

Yeah, quick google is saying it may not be possible with it

sage radish
#

@unkempt nova There's should be a Render Scale option in the URP asset

unkempt nova
#

Looks like I can do it easily from project settings anyhow though

unkempt nova
stark sail
#

I have made a spinner game. In the 1st rotation the objects seem to behave normally. But then they lose alignment and correct distance some of them per new rotation. After a few spins some overlap each other. I cant find what is going wrong with them.


private void FixedUpdate()
    {
        if (gameState == GameState.SPINNING)
        {
            Spin();
            if (isPrize)
            {
                /*If prize value is close to start make an extra round*/
                if (this.transform.localPosition == winTransform.localPosition)
                {
                    if (firstPass)
                    {
                        firstPass = false;
                    }
                    else
                    {
                        var message = GameEvent.Create(GameState.IDLE);
                        message.Publish();
                        firstPass = true;
                    }
                }
            }
        }
    }

    private void Spin()
    {
        float step = speed * Time.fixedDeltaTime;
        /*Let it snow*/
        transform.localPosition = Vector3.MoveTowards(transform.localPosition,
            boundaryTransform.localPosition, step);
        /*Reposition when it reaches the end*/
        if (Mathf.Abs(transform.position.y - boundaryTransform.position.y) < 10)
        {
            /*-400 because of the total number of values, the respawn position and the boundary position*/
            transform.localPosition = new Vector3(0,resetPosition.y-400,0);
            
        }
        
    }

unkempt nova
#

Ok, cool. It looks like OpenGLES3 allows me to profile. Unfortunately, phone doesn't seem to like it, screen's black. Here's the profile though

flint sage
#

What's your triangle count?

unkempt nova
#

No idea

#

Using Synty Polygon assets

sage radish
#

There should be a Rendering profile section that shows that

unkempt nova
#

You mean in the profiler?

#

Oh right, it lists tris in stats

#

That Tris count seems pretty damn high to me, but no idea

#

Up to 1.2 mil at some points, but I was only testing on mobile in the area showing me 675k

flint sage
#

Yeah that's high for mobile

#

especially with shadows

#

And those setpass calls seem high as well

unkempt nova
#

What even are those?

untold moth
#

Either avoid using unity terrain or tweak it's settings

unkempt nova
#

Hrm, ok. Thanks

somber swift
unkempt nova
#

Boss says he's gonna get some people on it

strong hinge
#

I have an editor menu that creates very complex objects. This script used to be a GameObject component but the menu option doesnt require play and the objects are then permanent.
The original workflow was >Create an empty GO, attach script component, set values and play. This allowed the values to be saved with the scene save.
The editor menu data doesnt store with the gend GO and I am trying to figure out a way to do this.
The only way I can think of at the moment is to create a parameter declaration list and share that between the editor script and a component script. This way the permanent GO keeps its values with it. But this is a lot of coding. I was hoping for a less complicated way. If any one has any ideas I would be thankful. Plus if I wanted to regen the GO the data would have to be restored into the editor menu data types.

untold pilot
#

You cannot easily deep copy classes in C# in general. You can convert it to bytes and make a new instance from the bytes. You are better off writing a method to return a class instance that sets all the values you want though.

public ClassA : MonoBehaviour
{
  private float mHealth;
  private int mLives;

  public void SetValues(float health, int lives)
  {
    mHealth = health;
    mLives = lives;
  }

  public void SetValues(ClassA target)
  { 
      target.SetValues(mHealth, mLives);
  }
}```
#

Worth noting the byte conversion method may not work for monobehaviours because you cannot use the new keyword with monobehaviours. The above method will work.

thick birch
#

Is this actually a smart thing to do?

#
private static readonly Dictionary<int, WaitForSeconds> waitForSecondsCache = new();
    public static WaitForSeconds GetWaitForSecondsCache(int value)
    {
        if (waitForSecondsCache.TryGetValue(value, out WaitForSeconds val))
        {
            return val;
        }

        WaitForSeconds newWait = new(value);
        waitForSecondsCache.Add(value, newWait);
#if UNITY_EDITOR
        Debug.Log("Created new WaitForSeconds with value " + value);
#endif

        return newWait;
    }```
plucky laurel
#

well kinda, but if you are at that level, youd rather use something better than native unity coroutines, like More Effective Coroutines, or UniTask

thick birch
plucky laurel
#

sure, but if you care about build size youd also probably care about performance

thick birch
#

plus this is just a simple add, really; and if it does improve performance then great

plucky laurel
thick birch
#

does it...cost?

plucky laurel
#

no alloc, faster, flexier, not target bound, chainable, extendable, and a single 7k line file

#

free one no, but it doesnt support realtime update

#

i think its $10 on sale now

thick birch
#

eeh i think ill stick with unity's

#

no way its 11 times faster though 🤔

plucky laurel
#

why not?

thick birch
#

whats the big difference?

plucky laurel
#

probably lack of marshalling for one

thick birch
#

whats that

plucky laurel
#

calling and transfering data between managed and native code

thick birch
#

huh....

#

does that apply for il2cpp builds?

plucky laurel
#

no idea

thick birch
#

if its so much better why doesnt unity buy it off like textmeshpro

#

weird

plucky laurel
#

good question, what other purchases of unity you know?

thick birch
#

occlusion culling one? maybe?

plucky laurel
#

how would you rate the purchase of Pro Builder?

thick birch
#

oh that one yeahg

#

hmm i havent used it yet but it sounds like a great purchase for some things

plucky laurel
#

yes but it doesnt have csg

thick birch
#

csg?

plucky laurel
#

so its not really suitable for level design

thick birch
#

how come

plucky laurel
#

csg is brushes

#

plop a box, plop another one, it goes in, it cuts

#

move it , the cut moves

#

no destructive, you dont think about polygons or geometry

thick birch
#

i guess it can work for games with mono color

#

¯_(ツ)_/¯

plucky laurel
#

pretty much any engine has it

#

what?

thick birch
#

like objects that have a single shade color/material

plucky laurel
#

no, you can assing materials to any surface

#

thats not the point

#

point is that probuilder is essentially a 3d editor, like blender, whereas it is advertised as level editing, despite lacking proper toolset.

thick birch
#

it can still made rudimentary levels, no?

#

low poly models

plucky laurel
#

so when you ask why unity doesnt buy the right thing for the right task, i cant answer you, as i havent seen that purchase apart from the TMP

#

on top of that, you have MEC and UniTask, for free, so

#

itll grow on you

thick birch
#

this worries me for the free version

#

how do i know if im using that right now in my scripts

plucky laurel
#

WaitForSecondsRealtime

#

i guess, if you in any method switch between awaiting WaitForSeconds to WaitForSecondsRealtime then yeah

#

anyway, im not here to sell it

thick birch
#

im using WaitForFixedUpdate

#

for my wandering coroutine

#

and then just WaitForSeconds on my idle one

#

¯_(ツ)_/¯

#

@plucky laurel i assume if i use MEC i wont have any use for this caching of the seconds im using?

plucky laurel
#

there are no returned objects

thick birch
#

🤔

plucky laurel
#

yield return 4F;

#

wait 4 seconds

thick birch
#

huh

#

and there are no allocations

plucky laurel
#

only initial

thick birch
#

no GC

plucky laurel
#

yep

sly grove
#

yield return 4f; will wait one frame, the number will be ignored

thick birch
sly grove
#

oh

#

my bad

#

shouldn't have butted in

thick birch
#

heheheh

stark sail
thick birch
sly grove
#

THere's still marshaling of data for il2cpp

thick birch
#

but i assume its not as bad

#

@plucky laurel say, i see theres 4 different options to call a coroutine...would this one use the FixedUpdate one?

private IEnumerator NextPassStart(float wait)
    {
        yield return new WaitForSeconds(wait);

        ResetMeteor();
    }```
plucky laurel
#

you have to specify a "segment" as a parameter when you start a mec coroutine

#

ie Start(Foo(), Segment.FixedUpdate)

thick birch
#

the heck is a segment supposed to be

plucky laurel
#

weird name i know, id rather call it Loop or something

#

unity update loops

#

has all the info you need

thick birch
#

thats what im doing lol

#

would unity's WaitForSeconds be a FixedUpdate segment?

plucky laurel
#

hint hint, google exists, im busy

thick birch
#

lol ok fair....

#

only thing i dont get is why it needs IEnumerator<float>

#

and whats the WaitForFixedUpdate equivalent i guess

thick birch
#

well this is weird, why is the Timing class on MEC make GC alloc 🤔

thick birch
#

Yeah not sure why you mentioned it adds no allocation on coroutines; seems to be doing it just as much

#

might be even worse since it doesnt cache it like mine

twilit jetty
#

i want to generate animation via code and make animation which changes material in slot X of skinned mesh renderer

#

but that its not good way and its just empty animation clip

sly grove
twilit jetty
#

because its made for game where i cant just publish code only animations/animators

sly grove
#

VRChat?

twilit jetty
#

yes

glacial sentinel
#

not really unity related but has anyone made a KD-tree before with 3d points?

sly grove
glacial sentinel
tough tulip
#

Oh if external app then sorry

#

or you can pack textures such that you can apply some offset to change the texture. as long as the shader type is same it will work

twilit jetty
#

nvm already got that working

wintry turret
#

Can I have multiple void Thing(uint3 id : SV_DispatchThreadID) in a Compute Shader? The point would be to have multiple Shader functions have access to the same data set by ComputeShader.SetData(). Right now I'm getting an error in the editor that says Shader error in 'FileName': Did not find shader kernel 'Kernel' to compile at kernel Kernel (on d3d11)

#

Do I have to make a bunch of different kernels?

sly grove
wintry turret
#

I guess the question is, can I have multiple Kernels in the same file reference the same data without using separate ComputeShader.SetData() calls? How about Structs?

#

Is this a valid .compute file?

{
    float2 position;
};

RWStructuredBuffer<Object> objects;

#pragma kernel MoveRight

[numthreads(1024, 1, 1)]
void MoveRight(uint3 id : SV_DispatchThreadID)
{
    Object obj = objects[id.x];
    obj.position += float2(.1, .1);
    objects[id.x] = obj;
}

#pragma kernel MoveLeft

[numthreads(1024, 1, 1)]
void MoveLeft(uint3 id : SV_DispatchThreadID)
{
    Object obj = objects[id.x];
    obj.position -= float2(.1, .1);
    objects[id.x] = obj;
}```
modern patio
#

Anyone know if vs2022 can disable file scoped namespaces ?

cosmic basalt
#

well you cant do that with unity anyway it only just moved to c# 8 on the newest version @modern patio

hollow wing
#

hi
so when one MonoBehaviour instantiates another GO in Update,
the Update method of the created object will not be called before next frame right?

#

just having issues with that as my GO is moved inside Update to a different position

#

so it seems that is reason for a initial jump

#

hm ig it makes sense in some way

#

for example execution order could not be guaranteed if it was called same frame

misty glade
#

if you instantiate() in update, unity isn't going to stop the update() cycle to start() and awake() that new object - that won't happen until ALL of the objects go through their start/awakes in the next frame

hollow wing
#

where do you take that info from?

sly grove
#

Awake actually happens immediately and before Instantiate returns, assuming the instantiated object/script is enabled/active

hollow wing
#

exactly

sly grove
#

Start/Update may or may not be called this frame, depending on the timing of when you called Instantiate in the current frame.

hollow wing
#

and start happens in same frame if active and enabled

misty glade
#

I'm .. 90% sure update will never happen on the same frame as you instantiate an object

sly grove
#

It's simple to test

hollow wing
#

about Update you're right

misty glade
#

but that should be trivial enough to test

hollow wing
#

I just tested it

sly grove
#

print out the Time.frameCount when you instantiate, and print it in Start/Update of the object you instantiated

hollow wing
#

Awake + Start same frame if active & enabled

#

but the reason I come here is for exceptions from this behaviour I don't know about

sly grove
#

I don't think it's documented

#

So your best bet is to check experimentally

#

and we don't have access to the source code to know for sure

hollow wing
#

does the above sound right to you though? (which is what I tested)

sly grove
#

Not sure

hollow wing
#

LateUpdate kinda does the trick for me btw

#

to have an Update called same frame after instantaite

hollow wing
#

thx

hot geyser
#

hello, how is best to change this code to work?
Do I use delegate? or callback? It is confusing. Thank you.

    return StartCoroutine(PowerWatch());
}

IEnumerator PowerWatch(float power){
    yield return new WaitForSeconds(1);
    return true;
}```
tough tulip
#
IEnumerator PowerWatch(float power, Action<bool> callback)
{
    yield return new WaitForSeconds(power);
    callback(true);
}```
You call it this way, 
```cs
StartCoroutine(PowerWatch(1f, (ev) => 
{
   //use bool here
});```

Next time onwards I'd suggest you to try [#archived-code-general](/guild/489222168727519232/channel/763495187787677697/) for quicker response
plush hare
#

Can someone assist me debugging this?

#

It's reads fine until 527 then stops working

strong pendant
devout hare
plush hare
#

it goes out of sync

#

something is going wrong

#

works fine up until then

#

max value for 10 bits is 1024

#

and I'm testing under that range

plush hare
fresh salmon
#

Max value for a number on 10 bits is 1023*

#

1024 values, ranged from 0 to 1023

#

And that's a console app, and it's full of bit shifting ops and whatnot

#

I would suggest debugging that with breakpoints

misty glade
#

@plush hare to take a step back, what are you trying to accomplish? There's a handful of libraries that can compress values without you needing to do all that work (protobuf, messagepack). I use MessagePack and love it.

#

And if you're trying to do a "flags" feature, enums in C# supports that natively

wooden cedar
remote oar
#

Can anyone help me with Network multithreading on Unity? I get insane lagg when im trying to receive alot of UDP movement packets

#

the actual handlers of the packets have to be run on the main thread

#

the packets itself are received on a different thread

#

however, it still causes alot of lagg

#

anyone has any idea?

#

its built with sockets btw

misty glade
#

probably need to paste some code, probably your incoming packet handler/dispatch

#

you probably also want to profile it and see what's going on tbh

#

if it's functionally working but laggy, the code itself might be hard to figure out what the issue is

remote oar
#

right

#

give me a sec

#
        {
            if (player == null)
                player = GameWorld.INSTANCE.GetLocalPlayer();

            using (Packet packet = new Packet(data))
            {
                int packetLength = packet.ReadInt();
                data = packet.ReadBytes(packetLength);

            }

            ThreadManager.ExecuteOnMainThread(() =>
            {
                using (Packet packet = new Packet(data))
                {
                    int packetID = packet.ReadInt();

                    if (UDPPacketListeners.PACKETS.ContainsKey(packetID))
                    {
                        PacketListener listener = UDPPacketListeners.PACKETS[packetID];
                        ThreadManager.ExecuteOnMainThread(() =>
                        {
                            listener.Read(player, packet);
                        });

                    }
                    else
                    {
                        Debug.LogError("Unable to read packet. Packet with id: " + packetID + " has no handler!");
                    }

                }
            });

            


        }
    }```
#

This is the incoming data function for my UDP handler

#

the logic of the packet listeners needs to be handled on the main thread since its doing stuff with gameobjects

#

TCP:

#
private bool HandleData(byte[] data)
        {
            if (player == null)
                player = GameWorld.INSTANCE.GetLocalPlayer();

            int packetLength = 0;

            receivedData.SetBytes(data);

            if(receivedData.UnreadLength() >= 4)
            {
                packetLength = receivedData.ReadInt();
                if(packetLength <= 0)
                {
                    return true;
                }
            }

            while(packetLength > 0 && packetLength <= receivedData.UnreadLength())
            {
                byte[] packetBytes = receivedData.ReadBytes(packetLength);
                ThreadManager.ExecuteOnMainThread(() =>
                {
                    using (Packet packet = new Packet(packetBytes))
                    {
                        int packetID = packet.ReadInt();

                        if (TCPPacketListeners.PACKETS.ContainsKey(packetID))
                        {
                            PacketListener listener = TCPPacketListeners.PACKETS[packetID];
                            listener.Read(player, packet);
                        }
                        else
                        {
                            Debug.LogError("Unable to read packet. Packet with id: " + packetID + " has no handler!");
                        }
                    }
                });

                

                packetLength = 0;

                if(receivedData.UnreadLength() >= 4)
                {
                    packetLength = receivedData.ReadInt();
                    if (packetLength <= 0)
                        return true;
                }

            }

            if(packetLength <= 1)
            {
                return true;
            }

            return false;
        }
#

socket creations on different thread:

#
        udpThread.IsBackground = true;
        udpThread.Start();
        
        tcpPacketSender = new TCPPacketSender(player, this);
        udpPacketSender = new UDPPacketSender(player, this);

        tcpThread = new Thread(new ThreadStart(ConnectToServer));
        tcpThread.IsBackground = true;
        tcpThread.Start();```
misty glade
#

slow down.. first, if you're going to paste in discord use ```cs

#

second, if you're going to paste that much code, paste in a website instead (pastebin/hatebin)

remote oar
#

sorry lol

#

do you want it in pastebin?

misty glade
#
private void HandleData(byte[] data)
        {
            using (Packet packet = new Packet(data))
            {
                int packetLength = packet.ReadInt();
                data = packet.ReadBytes(packetLength);
            }

what's this do? you shouldn't be editing parameters

#

also I don't understand why you're declaring a packet, tossing it away, then a few lines later declaring it again

#

you're doing the same in the TCP handler so it's probably not related to the performance hit of UDP, but it appears wonky

remote oar
#

yeah i've tried removing that and the data wont be read for some reason lol

#

but i can always improve that later

#

the server is sending NPC's which are moving via NavMeshAgent and sending its position aslong as the NPC has a destination

#

but right now it causes unity to freeze

misty glade
#

i don't see any obvious differences in the code that would explain the performance hit

#

you'll need to probably step through it and/or profile it

#

but.. there's some heavy duty code smells in this

remote oar
#

yes i know, the code isn't perfect

misty glade
#

if you're duplicating this much code you should be breaking it out into it's own method

misty glade
#

also this handler is doing a lot of allocation and expensive operations it appears (ContainsKey)

#

i don't know what TCPPacketListeners.PACKETS is, but depending on the structure and number of elements that are in it, ContainsKey could be expensive

remote oar
#

but thats not the point tbh

misty glade
#

face pace is no excuse for smelly code, because you end up in situations where it's impossible/difficult to debug things because the code is so messy

#

i get it, needing to prototype or PoC something is important but .. any time you get something small working you should go back and clean it up as best you can

#

imho

remote oar
#

yes i agree and i will eventually

#

this is one of the reasons why

#

because i get performance issues

misty glade
#

so i mean, right now you have two virtually identical functions, one for TCP and one for UDP and you have performance issues with UDP and no idea why.. so first step would be eliminate everything that's duplicated and put it in one method so that you get a better idea of the difference between the two methodologies

#

i'm not suggesting that you clean up the code just because it's a Good Thing To Do, but rather that you clean up the code so that the problem area becomes narrower and narrower until it's easy/obvious to see what the issue is

plucky laurel
#

isolate the problem

remote oar
#

networking is hard and its a learning curve for me

#

im just trying my best man

misty glade
#

networking is hard but it's like anything else.. learn how to do it, take it in small steps, clean as you go, and don't flail (try things without knowing what they do)

#

this isn't a personal criticism, just .. opinionated guidance 🙂

torpid sky
#

Are animations updated outside of Update() and more often than Update() is called?

misty glade
#

here's how I'd start - you have a method called HandleData() that appears to be:

  1. locating a player the first time it's needed
  2. adding the data to a receivedData structure
  3. getting the packet length by reading the data in that structure (and returning true?? if it's invalid)
  4. reading the received data and putting it into a byte array if it's big enough
  5. creating a complete packet
  6. reading an ID from it
  7. Finding the listener for that ID
  8. Sending the packet to that listener on the main thread
  9. trimming the read data into the received data structure
  10. Returning true??? if there's more data to read
#

all of those steps could be 2-3 line methods that are reused

#

(and shared between tcp/udp)

torpid sky
#

I have a few Transforms attached to my weapon and every frame I draw a line from the current position to the previous position. However, there are gaps between the lines which doesn't make sense to me

misty glade
#

i like those debug lines, btw

#

i'm assuming for hitbox collision debugging?

torpid sky
#

yeah

#

I do raycasts that are equal to those lines

misty glade
#

and i assume you create the start and end vector in each update tick?

#

ie, they should be connected

torpid sky
#

yeah

#

I have an array of "previousPositions" that I set to the current positions at the end of update

misty glade
#

yeah - i imagine the loop (in the URL i linked above) in OnAnimatorIK is getting done a couple times in a frame, leading to the gap

torpid sky
#

dunno

#

I feel like even if the animator was updated multiple times, there should still be no gaps

#

maybe I have a bug

misty glade
#

so .. there's also a tiny note in the Physics animation cycle

#

the cycle can happen more than once per frame if fixed time step is less than actual update time

#

since you have what appears to be some fancy meshes/graphics/lighting, it's possible that you're getting two frames of physics and animations for one frame of update()

torpid sky
#

yeah but

#

if I save the positions in the previous update call

#

and then in the current update I draw lines from the current to the previous positions

#

I feel like there should be no gaps

#

even when FixedUpdate or some animation update is executed multiple times in between

#

dunno

#

maybe I have a brain worm

#

the current positions are the previous positions in the next update

#

so there should be no gaps

misty glade
#

ah, yeah, good point - i thought you were setting the "start" vector in one part of the cycle (fixedupdate or update) and setting the end in another part (update or lateupdate)

#

probably buggu 🐛 then 🙂

torpid sky
#

xD

glad moth
#

Hey! 👋
I have a question for a pickup system, is it more optimized to pickup items with a collision trigger that is on the item or on the player directly? 🤔
(It must be taken into account that there will be a lot of items).

torpid sky
#

dunno, I don't think there is a big difference

#

you need colliders on the player and the items anyway if you go about it like this

#

I'd put a trigger on the player and a trigger on the items and put both in a separate layer "Items" or something

#

and put a trigger enter event on the player

glad moth
glad moth
torpid sky
#
    void SetPreviousPositions()
    {
        previousPositions.Clear();
        for (int i = 0; i < hitTrackers.Count; i++)
        {
            previousPositions.Add(hitTrackers[i].transform.position);
        }
    }

    void HitTrackerCast()
    {
        for (int i = 0; i < hitTrackers.Count; i++)
        {
            Vector3 direction = (hitTrackers[i].transform.position - previousPositions[i]);
            float distance = direction.magnitude;
            Raycast(hitTrackers[i], direction.normalized, distance);
        }

        SetPreviousPositions();
    }

    void Update()
    {
        HitTrackerCast();
    }

Do you see something obvious that's wrong? 🤔

#

I rly don't see why I have gaps in my rays

median cosmos
#

hey there, I'm currently having this problem:
I'm currently working on a neuronal network where the AIs try to learn to walk

#

the basic neuronal network works fine

#

but the legs & body should only collide with the legs/body of its own Ai/parent object

plucky laurel
median cosmos
#

can I somehow create "parent-collision-matrixes"?

plucky laurel
#

you can use Physics api to selectively tell objects to ignore each other

median cosmos
#

ah I never heard of such a function, thanks!

#

hmm

#

@plucky laurel isn't there a more efficient way to do this since I have 50 enemies at the same time

misty glade
#

think of if you were swinging a bat - the velocity at the tip at a moment in time is going to be perpendicular to the bat, but the bat is moving in an arc, so the next "tick" start vector won't be the end vector of the first tick

median cosmos
#

and everyone shouldn't collide with anyone, meaning 50*50 = 2500 checks

misty glade
median cosmos
#

can't I like just give the prefab a property or function called 1 time which disables all collision with other prefabs of the same type?

plucky laurel
#

should happen once on each agent init

median cosmos
#

ahh

#

so IgnoreLayerCollision?

plucky laurel
sly grove
median cosmos
#

yes of course

sly grove
median cosmos
#

so this overrides the layer matrix options?

sly grove
#

it doesn't override them, it just runs completely separate physics simulations that don't interact with each other at all

median cosmos
misty glade
#

@torpid sky was thinking about this in the shower - if you want to have a smooth line, you'll want to just track the previous and current locations and draw a line between them (instead of raycasting based on velocity and orientation).. although if you're using it for hitbox detection, it's potentially going to feel weird since the collision will happen "after" the blade has passed through it

torpid sky
#

something feels off lol

narrow lodge
#

Anyone know if there's a way of sampling a light probe's color/brightness given an arbitrary position?

misty glade
#

hm, oh, i see - i thought you were getting the magnitude from somewhere else, not just subtracting the vectors and normalizing the distance in the difference vector

torpid sky
#

it goes from previousPositions[i] -----> B where B is current position in this tick, and in next tick from B to current position in this tick, etc.

misty glade
#

maybe what I'd start out doing is outputting the [0] vectors location each time you call HitTrackerCast() and seeing if previous[0] really does = hittrackers[0] before the shuffle

#

(and maybe outputting a line in update() just to ensure you're not inadverently calling this from somewhere else or .. having some other weird unrelated bug)

plucky laurel
#

does changing the animation framerate affect it?

misty glade
#

ie, you should see something like
--update
--hittracker: 0,0,0 previous null
--update
-- hittracker 1,1,1 previous 0,0,0
--update
--hittracker 2,2,2 previous 1,1,1

#

etc

sage radish
misty glade
#

@torpid sky also where's your DrawRay() call?

median cosmos
#

hmm

#

it gives me an error saying the object "body" hasn't got a collider even though it has

#

oh wow

#

silly mistake

#

i used 3D physics in 2D😂

torpid sky
# misty glade <@!198410655869435904> also where's your DrawRay() call?
    void Raycast(HitTracker hitTracker, Vector3 direction, float distance)
    {
        RaycastHit[] raycastHits = Physics.RaycastAll(hitTracker.transform.position, direction, distance, hitboxMask);

        #if UNITY_EDITOR
        if (drawDebugLines)
        {
            Debug.DrawRay(hitTracker.transform.position, direction * distance, debugLineColor, debugLineDuration);
        }
        #endif

This function is called in HitTrackerCast()