#archived-code-advanced
1 messages · Page 153 of 1
rip
do you mean something like:
vector2 pos;
do{
pos = (random vector2)
}
while(mineLocationsHashset.Add(pos))```
oofx3
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
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...
yeah heavily saturated is one thing that worries me but im testing the code yallve given me now
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
you might be able to just evaluate it lazily
like only generate mines in the area revealed when they click
you can't do that. minesweeper is deterministic
i think you're forgetting that you can flag mines
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
the empty spaces will display numbers to show how many mines they're touching
plenty of games have a 'please wait while we generate the map' bar
i can tell you how minesweeper actually does it
or you could be tricky about it and do it behind the scenes on the menu screen or whatever
yeah i know, but im trying to challenge myself to make a minesweeper that lets you make as big of a map as you want without it lagging at any point
they have a bunch of binary files and they just strip off zeroes and 1s and 1s are mines
ezpz
where are those files from though? are they finite and ship with the game?
there ya go
you figure one 100x100 level is litearlly only 10000 bits
yeah, the clever part is that to generate one, you only need to do a coinflip X times
so there's your answer
just do x coinflips and you don't have to worry about overlap
it's not that simple because you need to control for how many mines are in a level
yeah, one strategic factor that the player has is knowing how many mines are actually on the board
it has to be exact
does it need to be known ahead of map generation though? or can the map generate roughly a similar amount each time?
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
this is how i handled realtime perlin noise
i would pre-generate noisemap textures and randomly select them and offset them in realtime
'just do it ahead of time' is often the best optimization
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
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
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
could you just pick a starting spot and block it out before you add any mines?
i think the idea is that admiral wants the first click to be safe
oh i see, no matter where they click it needs to be valid...it doesn't start with anywhere open
right, thats why im currently doing mine generation on the first click
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
i would probably just have your first click be an explosion or something
and it 'clears' those tiles
oh that's an idea
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
even simpler
if they are playing with safe mode on, they probably wouldn't mind that it's a little rng
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
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
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
classic minesweeper definitely doesn't
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
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
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
yeah i can see how that would be extremely efficient
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
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
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
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
{
"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
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
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
gotcha, looking up info about that now
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
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
yes
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}]}
yooo this is dope, thisll be a great way for me to learn how to save to JSON
indeedily
so when you want to load up a level you might have like an ACTUAL grid class that does something like
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
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
right, thats what i was thinking. They way youve set the savinging function seems to make something like that trivial
yep
i was also thinking of this, as another feature would be to have custom maps with missing tiles
the whole idea of a DTO is the file knows its data, and it knows how to save and load itself
Well thanks for writing that up for me man, im definitley going to be implimenting that
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
right, i can understand that
lol. yeah I think you may be right.
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
thanks again man, good night, sleep well

Does it? I remember it only having its own serializer which doesnt even support half the types properly
Maybe this changed with the latest version
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
There are naturally many ways, I’ve recently been in favor of having an explicit state machine somewhere that describes all the signals and transitions in one place and orchestrates all the instantiation and side effects.
when there are lots of state, say 10+ I prefer using events/state responses to set some booleans/enums within the behaviour and a simple function which checks all of the state using ifs/switches and do the needful.
I find this quite simple and it also helps me keep each state seperated out from each other even tho certain behavior requires mixing them up
Unable to resolve reference 'Microsoft.Extensions.DependencyInjection.Abstractions'. Is the assembly missing or incompatible with the current platform?```
Anybody know how to solve this?
add the dll for Microsoft.Extensions.DependencyInjection.Abstractions to Assets/Plugins, has to be a version that works for your build target
It's already there in Assets/Plugins/AwsAssemblies
Also, this is my Mac machine
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
you mean unity for mac?
so how do I get AWS to work with Unity on my mac?
This works on my windows machine
use the standard2.0 version if it is available
the standard2.0 version of the AWS SDK
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
and what version of Microsoft.Extensions.DependencyInjection.Abstractions?
Looks like...it's not there in my AwsAssemblies
you have to supply any .net libraries with your application that are not installed on the host computer and accessible in a registered library path
But why? it's not there on my Windows machine too. Does my Windows machine implicity inject something?
on windows it is probably installed as part of windows or you installing visual studio and is discovered automatically
yup, sounds like you're right
any idea what I have to download on Mac now? Just this Microsoft.Extensions.DependencyInjection.Abstractions?
i usually download the nuget that contains it and extract the dll/version i need and copy that to the asset folder
How do I determine which version I need? That isn't mentioned in my stacktrace
the standard2.0 version
it has additional dependencies you may have to install
lets hope for the best
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?
I'm following this:
https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection.Abstractions
Under .NET CLI
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.
I have Rider installed
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
actually forget rider..if I were to add it using the .NET CLI, where in the Unity project would I add it?
If I do it in the root, it says "too many unity projects detected"
It's own serialized uses newtonsoft just an earlier version yeah. And it has trouble serializing generics like dictionaries
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
probably best to add it to Assets/Plugins/<NameOfLibrary>
Yeah I prefer to have a state machine as well. The main issue is keeping track of what menus are open and sleeping vs the states they represent (I intend to load prefabs dynamically and delete them, unless they're in the history states)
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.
if i recall, unity doesn't include a specific version of newtonsoft as a convenience. they build it into the engine. they do inspector serialization via JSON so they have an engine tool that sits on top of that version of newtonsoft
but yeah i like using new newtonsoft because you can serialize while maintaining SOLID principles. instead of having public members you can serialize properties
Most serialization is yaml, they only do json for a few things
Most of those were around before serialize reference
oh gotcha
i do know they designed scriptable objects to be trivially serialized to/from json which is very handy
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.
this is not a php discord
If your issue is related to Unity, then please elaborate.
Else, you'll need another server
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.
you're only getting data. not sending any
Do you know how I could do that? 🙂
Probably with UnityWebRequest.Post
Something along these lines?
Looks good to me
hm, still doesn't seem to be working.
Have you got any debugging measures in place server-side?
Like, dumping the contents of $_POST or whatever it's called
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?
Apart from passing the form and yield return send it, nothing else
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
split it up over multiple frames using a coroutine
Hmm I see.. So if it does like 1million for loops, I should WaitForSeconds(0.1) every 100 loops
For example... ?
i hope it does one loop with 1 million iterations
no you don't WaitForSeconds(0.1)
you just yield return null to wait a single frame
networking is straight up impossible man I literally just want to have a user login
been a good run, I give up lol
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.
huh one of the cases where callstack would not help
type GameObject.Destroy(), right click, find all references, and.. find it
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.
hm, maybe i dont understand you right. Searching on the OnDestroy doesnt give anything, cause its an Event. just typing GameObject.Destroy() gives me all points in the code where Destroy is called(like 160 entries)
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
UP !
No idea ?
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
moved to #archived-code-general
no unity json doesn't use newtonsoft. infact Unity json is very much more efficient in terms of memory compared to newtonsoft's latest version even
Why does unity package newtonsoft out of the box then?
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
well what you can do is use time slice (yield return null) based on a frame time budget.
Instead of yield every 100 iterations, you can basically make use of StopWatch to yield every X milli seconds. That way you can ensure a good framerate and also fastest possible iteration on any device scaling according to the performance
You can use OnDisable.
Any object which is being Destroyed is internally scheduled to be killed at the end of frame, not immediately, thus killing stack trace.
But OnDisable is called immediately when you call Destroy
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?
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)
calloc > malloc :3
is that for me?
it's just joke for malloc boy but not for you sorry ..
oh whoops. didn't notice the previous participants. my bad
ahah np
Hi, Thanks for your answer. I already tried that. It was suggested in a forum post. Unfortunately i dont get the Call Stack there. Someone else tried it and didnt get it either. He suspected that this behaviour changed in Unity 2020...
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
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
[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);
}
the behavior is same in 2021 as well. I suspect your gameobject isn't active in the first place. OnDisable is never called twice without OnEnable being called
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..
did you try loading the same issue in unity editor of same version?
try to load the same in a non headless version as well. if it works in both, it's probably a bug with headless builds.
Also make sure you're running on latest LTS or any previously known versions where you know this was working fine
this could also happen if your project files get corrupt. so try a simple rebuild aswell
yeah it was some weird unity bug
when i called the load function somewhere else it suddenly started working again
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
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?
The Unity manual covers this for Android and iOS, start there
Thank you. What should I search for? I tried doing my own research but I kept getting different search results than what I'm looking for
Native plugins
yeah i saw that, just changed that so, thank u !
so you think u can convert unityevent<T> in unityevent ?
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
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
look into the sources
can someone suggest learning resources for native plugins? it's my first time trying something with native api. This is what I am trying to achieve
into the sources ?
yes ui package sources
on github or use decompiler
use them to find whatever you need
oof, never did that
going blind only gets you that far
okay okay, i'll try to do what you say !
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```
don't use file extension for Resources.Load
...
that was it
can't believe I wasted like 30 minutes
Oops
So... for async/await. How do we know if the thread that wakes up after an await is the game thread?
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
Cool. Thanks!
you can also get the managed name of CurrentThread. Unity's main managed thread name is null (or empty) , and TPL threads often have some name (Worker Pool something)
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;
}
}```
You need some way to check if GameObject enemy is the enemy which is casting or not.
For example:
void TargetEnemy(int casterEnemyID)
{
...
foreach(var enemy in enemies)
{
if(enemy.ID != casterEnemyID)...
}
}
Thanks very much, I just saw that there's a possible "this.gameObject" that I may be able to use...?
if you have a definite class reference of Enemy, then yes you can do something like
if(enemy!=this)
But if you don't have a reference of the class, like a multiplayer game then you might need some identifier somewhere in the logic
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
It's a very basic mistake. There's nothing advanced about this code no offense.
!gameObject is a wrong check because !gameObject translates to gameObject==null which isnt true in your case
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;
}
}```
what class does TargetEnemy function exist in?
in Enemy?
At this point I really should put TargetEnemy as it's own class but, it is in a subclass "EnemySpells"
then you need reference to Enemy
I assumed your function also resided in Enemy script
I do reference it..?
private Enemy enemy;?
Just to mention... Only enemies that can cast will have this script attached
Here's my enemy script https://gdl.space/luxuhizeyi.cs
Should I ask in another chat?
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)
I just learned about the ~ feature but don't know what it exactly does, can someone explain?
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers
There's little reason to use them generally. IDisposable is generally more appropriate.
Alright thanks! I just didn't even know it was a feature in .NET
It's a expected feature in any OOP language. They call em the destructor and it is normally paired with a constructor.
Tell that to Java
More context?
Java is an OOP language that doesn't have destructors
Haha, alright.
Something that isn't guaranteed to be called 😦
The finalize method might be called on a finalizable object only after an indefinite delay, if at all
It's also deprecated
I would presume that's the same caveat in C#, no?
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
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
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.
Technically a finalizer... still at the mercy of the GC to run. Not like C++ where it's deterministic. (Also, Java has finalize() on the base Object class.)
As always -- profile it and measure. You can't REALLY know for sure until you do. That said, in general it will be faster if you can send a LITTLE data to the GPU and get that stuff happening there (unless you need to know the vertex positions on the CPU for some other reason, like collision or whatever).
But it's certainly doable in a realtime sense.
If you're talking about a million triangle mesh... then maaaaaaaybe reconsider lol.
You mean i can modify updated vertices with a shader?
You can modify any vertex with a shader, yes.
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.
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.
But i suppose i better start learning how to write shaders and such.
thanks for the info
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
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?
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.
Oh wow, i thought gpu's only did much more basic stuff.
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
You're accessing an Index of your array that's outside the bounds of the array
im trying to run a basic ar scene with arcore but the screen is black and get this on logcat
how do i change the color of a GUI slider? changing GUI.color doesn't do anything
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
Is it possible to extend unitys built in physics material with additional properties somehow?
"sort of"... you grab the object during interactions with other objects, by way of collision "callbacks", and make changes to how it's going to react in there, in accordance with what you want. It's messy, initially, but it gets easier the more you do it.
Could probably extend it. Doesn't seem to be sealed.
Might need to write a custom inspector for it though.
public class CustomPMat : PhysicMaterial
{
public float radioactivity;
}
I don't need it for custom collision behaviours, but for different surface properties for a racing game
Right now i'm using a dictionary with the physic materials as keys and a struct with the additional properties as the value
That's what i tried but i couldn't figure out how to create an asset of the derived class
Did you try the CreateAssetMenuAttribute?
https://docs.unity3d.com/ScriptReference/CreateAssetMenuAttribute.html
That or use this:
https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
The second one might work, thanks
The first i tried but it's only for scriptable objects
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
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.
Start out trying to make ice-like behaviour, and then reign it in from there.
And tap into your inner Raikkonen
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
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
i dont understand why do you need to extend it
a wrapper should suffice
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
Like this?
public class AdvancedMaterial : PhysicsMaterial {
public MyFancyMaterialProperty AdvancedProperty;
}
That's what I suggested earlier. The issue was we were not sure how to serialize instances into assets.
ah, right
Since PhysicsMaterial inherits from Object. I don't know if the last suggestion worked for them or not..?🤷♂️
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
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
Interesting. But I guess that's to be expected. Might need to dig into assets import pipeline if you want to change that.
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.
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
Anything but default extensions and built in unity stuff just shows up as a blank file in the poject window, not sure if there's a way around that
I tried .asset but that has the same issue as .physicMaterial
I see.
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 ?
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.
so how do i fix it?
yeah, it was just an easiest way to explain the thing^^
okay, thanks for your answer dude !
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
you can clamp the index between 0 and the list.count, search mathf.clamp
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
do you have a reference of what you want ?
......how do i do that XD
https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
index = mathf.clamp(index, 0, list.count)
or its maybe : index = mathf.clamp(index, 0, list.count - 1)
I'm not sure
I tried to explain procedural animation in 10 steps.
Check out my twitter: https://twitter.com/CodeerDev
This is #archived-code-advanced, you're expected to know at least how to look things up. If you're struggling with basics, use #💻┃code-beginner.
ok
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
when the target is far enough, you are just doing like "legposition = targetposition" ?
show me how you are doing the lerp
leg.position = Vector3.Lerp(leg.position, hit.point, 30f * Time.deltaTime);
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
so kinda like what i said here right
I tried to implement it and its a bit glitchy and doesnt work great
not for the x and z pos, only the y pos
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
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
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
idk its just causing some timing issues
having 2 lerps
trying to work on it now
normally of its done correctly, it will work
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?
not really
then what
wait, doing a test
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
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.
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
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
you would read the input in some way that i don't remember, it's gonna tell you
yeah thats the whole crux, there's so much to read and so little documentation
i find that it's pretty well documented, though samyam's channel helped me a lot
lemme get a link
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
How to use the new input system in Unity! Next video will show how to make a character controller using the input system.
📥 Get the Source Code 📥
https://www.patreon.com/posts/38331467
🔗 Relevant Video Links 🔗
ᐅNext part
Make a SIMPLE Character Controller using Unity's NEW Input System
https://youtu.be/w1vC32e11wU
ᐅPlaylist
Unity Beginner Mini...
one of her many new input system tutorials
Dumb (of me)! Basically how we used to do it.. InputAction.CallbackContext obj. ReadValue<float>(); thanks
Thanks, i'll play it in the background 🙂
Hmmm, reading the float Does identify the keypress. But it doesnt identify the Key Up (canceled action), since the value then is 0
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 :))))
Guys how can I do world scrolling with vuforia can you give any kind of referance or advice to me ?
(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?
@regal olive sounds like an interesting homework question.
woah do you mean to say you think my code validates as homework given by a teacher? - dayum that makes me smile 🙂
nothing so flattering was intended 😛
if you're looking for an 'easy' way to find maximums
System.Linq has a lot of useful stuff
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
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
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 :)
Axes don't have keyup events; they're an axis. It doesn't make sense to look for a keyup on a joystick, or a mouse delta, or an accelerometer. If you want the behaviour of two buttons it's better to just use two buttons, not an axis.
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
Question migrated from #💻┃code-beginner. They're using a steering wheel and the legacy Unity Input Manager
yeah yeah
The axis does not report the value right.
That's the information you need to include in your original message.
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
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")
Is your problem that the Addressables aren't being built when you make a build from the editor?
Yes
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.
Okay, let me try
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);
}
}
you know it would be so much better if you just added "cs" at the start of that message after "``" thingy
NICE 😄
color
thanks for the tip!!
np bro
okay anyone familiar with writing custom HID for a controller or something along those lines ?
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!
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?
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>();
}
Perhaps explain what're you looking for in particular; relative to URP.
you have to convert the position of the position of the object to screen position:
use camera.worldtoscreenpoint or camera.main.screentoviewportpoint, something like that i don't remember
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)
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
This seems to be compilation stuff happening in the editor
That's what I was thinking, but it's in play mode. I don't get it
Are you profilling the build from the phone?
Well you need to connect the profiller to the phone running a dev build
That way you can see what is going on
Fair point. That sounds like a pain. Thanks though
Its not that bad, also Editor overhead is a real issue and any data you get from profiling in editor you should take with a pinch of salt
Cool. Time to start researching how to do it haha. Thanks
Just make a development build then it can connect via ip its not hard
Profilling mobile in the editor on a pc aint worth jack if you ask me
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
Yeah. You just have to profile the right thing
And that thing is the dev build running on the actuall device
Agreed, also figure out what is taking long, CPU or GPU?
From there you can start using mroe specialized tools
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
The profiler can run as a independat process to reduce the editor overhead
It's probably fine
Its gonna be fine
Good news. Thanks
Ive never seen a case with such a huge diff in perf. Report back with what you find Im interested haha
I'd expect it's some graphics thing that's just badly supported on mobile
URP with multiple stacked cameras?
Yeah that's expensive
What else is in that stack?
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
Right, step one is disable post processing and ssao
Should have a look at the GPU profiler too
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
Yep, gonna just disable all post processing stuff and try it
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
What phone are you running on?
Samsung Galaxy A50
Mid range specs with a relatively large screen will kill performance with postprocessing
Makes sense. Wasn't sure where on the spectrum it was. Felt mid range
Fullscreen pp kills the mobile. Especially on tile based renderers
Getting this now, with deep profiling build on phone. Is that just profiling crap?
This is with all post processing disabled
Seems like it yeah, it's creating some class instances in there
Always profile without deep profiler first. There's usually more than enough info.
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
Nothing at all..?
Meaning there was no performance issues..?
Deep profiling is quite expensive
Yeah
I can imagine that in a rendering pipeline it builds up really quick
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
Yeah, didn't post without it. Should be ready in a sec
Mobile build takes like 8-9 minutes each T.T
Lucky you
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?
Seems so. But there might be both.
Try looking at the gpu profiler module first. If it works on your device.
Digging a bit deeper
If not, either find native gpu profiling tools or just look at your project and optimize anything that could be have on the gpu.
GPU just says no frame data available. Sounds like not
Mihgt not be enabled in the build
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)
Yeah, makes sense
There's a bunch of platform specific profilers that you can use
Know of one, so I can get that ball rolling?
Before I just google "Unity platform specific profilers"
Awesome. Thanks
They tend to not be as user friednly as Unity's tools though
Ah. Boo
I think you need to use the one that is compatible with your device chipset
*from the producer of the chipset
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
Ah, makes sense. I think I'll try poking around for player settings and stuff before I open that can of worms
I never had any luck with these tools for some reason. Maybe my device is just poopoo 😅
just drag OpenGL above Vulkan I'm thinking here, right? Or do I need to remove it
I'd remove it just in case
Yeahhh they can be a bit of a pain to deal with
Ok, will try that out. Triggered a reimport looks like. Think this is gonna be a while lol
One thing that might boost performance is switching to Gamma color space.
That shouldn't do that much
Perhaps. It did help me in one of my projects a lot and I'm using it ever since on mobile.
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
Yep.
Share some info on your project: what shaders are you using, what's the average vertex count, etc...
Probably someone else but I've been using Unity for 7~ years
With not much prior gamedev experience
Ah, ok. Must be someone else
Back when the Unity IRC was still thriving
Good point, will do later. Gotta gather all that info. I was just kinda tossed into this blind
@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.
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
Ah, ok. Thanks 😄
Are you using URP?
Yeah, quick google is saying it may not be possible with it
@unkempt nova There's should be a Render Scale option in the URP asset
Looks like I can do it easily from project settings anyhow though
Ah, ok. Thanks. Will check that out
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);
}
}
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
What's your triangle count?
There should be a Rendering profile section that shows that
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
Yeah that's high for mobile
especially with shadows
And those setpass calls seem high as well
What even are those?
and QuadTreeNode.Render seems to be related to unity terrain..?
https://answers.unity.com/questions/1298414/im-bottlenecked-by-quadtreenoderender-what-is-it.html
Either avoid using unity terrain or tweak it's settings
Hrm, ok. Thanks
yep, that seems pretty high for mobile. realtime shadows are also very rare on mobile games because they are pretty expensive. what are those objects? have you considered using lods to reduce details on further objects?
Boss says he's gonna get some people on it
Research Gimble Lock.
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.
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.
just use any serializer
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;
}```
well kinda, but if you are at that level, youd rather use something better than native unity coroutines, like More Effective Coroutines, or UniTask
eeeh doesnt that add to the build sizes
sure, but if you care about build size youd also probably care about performance
plus this is just a simple add, really; and if it does improve performance then great
does it...cost?
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
why not?
whats the big difference?
probably lack of marshalling for one
whats that
calling and transfering data between managed and native code
no idea
good question, what other purchases of unity you know?
occlusion culling one? maybe?
how would you rate the purchase of Pro Builder?
oh that one yeahg
hmm i havent used it yet but it sounds like a great purchase for some things
yes but it doesnt have csg
csg?
so its not really suitable for level design
how come
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
like objects that have a single shade color/material
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.
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
this worries me for the free version
how do i know if im using that right now in my scripts
WaitForSecondsRealtime
i guess, if you in any method switch between awaiting WaitForSeconds to WaitForSecondsRealtime then yeah
anyway, im not here to sell it
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?
there are no returned objects
🤔
only initial
no GC
yep
yield return 4f; will wait one frame, the number will be ignored
we talking about that coroutine asset
heheheh
there is no rotation happening though. Only Y movement
while ur here, we were talkinga bout an il2cpp thing that neither of us knew
THere's still marshaling of data for il2cpp
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();
}```
you have to specify a "segment" as a parameter when you start a mec coroutine
ie Start(Foo(), Segment.FixedUpdate)
the heck is a segment supposed to be
weird name i know, id rather call it Loop or something
unity update loops
you can btw just read this http://trinary.tech/category/mec/
has all the info you need
hint hint, google exists, im busy
lol ok fair....
only thing i dont get is why it needs IEnumerator<float>
and whats the WaitForFixedUpdate equivalent i guess
well this is weird, why is the Timing class on MEC make GC alloc 🤔
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
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
Why not just do the animation yourself in your code?
because its made for game where i cant just publish code only animations/animators
VRChat?
yes
not really unity related but has anyone made a KD-tree before with 3d points?
nope but there's some example code and pseudocode on wikipedia
ah yes that could be very useful thnx
why not write a shader and apply keyframe to switch a exposed parameter in keyframes?
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
nvm already got that working
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?
Sounds like you just didn't call FindKernel with the same name as your shader function
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;
}```
Anyone know if vs2022 can disable file scoped namespaces ?
well you cant do that with unity anyway it only just moved to c# 8 on the newest version @modern patio
Sure I don't see why not
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
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
where do you take that info from?
Awake actually happens immediately and before Instantiate returns, assuming the instantiated object/script is enabled/active
exactly
Start/Update may or may not be called this frame, depending on the timing of when you called Instantiate in the current frame.
and start happens in same frame if active and enabled
I'm .. 90% sure update will never happen on the same frame as you instantiate an object
It's simple to test
about Update you're right
but that should be trivial enough to test
I just tested it
print out the Time.frameCount when you instantiate, and print it in Start/Update of the object you instantiated
Awake + Start same frame if active & enabled
but the reason I come here is for exceptions from this behaviour I don't know about
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
does the above sound right to you though? (which is what I tested)
Not sure
Based on https://docs.unity3d.com/Manual/ExecutionOrder.html
I think it might be possible for Update to be called on the same frame if you instantiate early enough, say in Awake or FixedUpdate
LateUpdate kinda does the trick for me btw
to have an Update called same frame after instantaite
hm yeah that makes sense
thx
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;
}```
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
U seem to be asking for a float argument in the declaration of the coroutine and u dont give one while calling the coroutine idk if that will help but..
What do you mean stops working
Look at the Main() function, I have a for loop to test it
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
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
@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
That doesn't have anything to do with Unity and wouldn't run in Unity. But I'll say the same as other folks, what exactly are you trying to do?
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
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
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();```
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)
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
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
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
yes i know, the code isn't perfect
if you're duplicating this much code you should be breaking it out into it's own method
you also shouldn't be just writing code that you don't understand why it works/doesn't work
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
i havent really looked in to it much, just a fast pace at that moment
but thats not the point tbh
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
yes i agree and i will eventually
this is one of the reasons why
because i get performance issues
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
isolate the problem
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 🙂
Are animations updated outside of Update() and more often than Update() is called?
here's how I'd start - you have a method called HandleData() that appears to be:
- locating a player the first time it's needed
- adding the data to a receivedData structure
- getting the packet length by reading the data in that structure (and returning true?? if it's invalid)
- reading the received data and putting it into a byte array if it's big enough
- creating a complete packet
- reading an ID from it
- Finding the listener for that ID
- Sending the packet to that listener on the main thread
- trimming the read data into the received data structure
- 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)
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
https://docs.unity3d.com/Manual/ExecutionOrder.html#AnimationUpdateLoop Animations are after Update, potentially multiple times depending on things
i like those debug lines, btw
i'm assuming for hitbox collision debugging?
and i assume you create the start and end vector in each update tick?
ie, they should be connected
yeah
I have an array of "previousPositions" that I set to the current positions at the end of update
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
dunno
I feel like even if the animator was updated multiple times, there should still be no gaps
maybe I have a bug
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()
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
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 🙂
xD
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).
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
mmhh, it's true but I had the question because I see a lot of people putting it on the item directly.
Oh ok I remember, thx
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
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
should be more effective to use preconstructed Ray, you would skip double sqrt
can I somehow create "parent-collision-matrixes"?
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
Oh, I didn't know this is how you're doing it. This should be straightforward - you're casting a "straight" vector ray of distance in direction, but there's no guarantee that the endpoint of that cast is the start point of the next cast
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
and everyone shouldn't collide with anyone, meaning 50*50 = 2500 checks
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?
you put them all on the same layer, and allow them internal collisions with that method
should happen once on each agent init
same layer. in the matrix disable interlayer collisions. use this https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html to allow collisions per object
Have you looked at the Project Settings -> Physics layer collision matrix yet?
yes of course
.
One option is to use multi-scene physics so that each AI has its own entirely separate physics scene https://docs.unity3d.com/Manual/physics-multi-scene.html
so this overrides the layer matrix options?
it doesn't override them, it just runs completely separate physics simulations that don't interact with each other at all
isn't that ver yunefficient as well since there are 50 objects
@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
Not really
but that's what I'm doing
I don't understand, because previousPositions[i] is the start point in the current tick, and in the next tick it's the end point - hm wait
something feels off lol
Anyone know if there's a way of sampling a light probe's color/brightness given an arbitrary position?
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
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.
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)
does changing the animation framerate affect it?
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
Light probes are directional. Do you mean you want to sample the color in the direction from the light probe to the arbitrary position?
@torpid sky also where's your DrawRay() call?
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😂
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()