#archived-code-general
1 messages ยท Page 184 of 1
that's why i suggested an interface
do you know how to reference another script to call functions on it
yeah i do
okay
but i want it to be dynamic
to be able to call the same name of a method
what?
but the script is different
its UI right?
Should've looked it up before saying this
i thought its just UI
Glad it can help though
is there an Abs method for vectors?
What, like (-1,-1,-1) to (1,1,1)?
yes
I guess you can just Abs each float in it
confused what the usecase for wanting abs for vectors is
some sizeDelta calculations when stretching the ui panel
Hey Folks, I have an arena game where there is a player controlled object, and things in the arena that you pickup by driving over them. Is it best to put the collision script on the player object, or the prefab of the pickup items?
https://gdl.space/iqupazacit.cs I'm trying to do a total war or like age of empire like movement, but I can't like even think of how to add diagnol line, so far all I can do is line my troops up horizontally, any ideas?
ay
i want to check if the collider matches the collider component created by an script on incoming trigger collision
is it possible?
like not if the incoming collider matches or anything, but if the collider that reciever the collision is the same as an created collider component.
You could add a component to that collider's object and check if it exists, for example. Or use tags
i mean with multiple collider components
i want to make an radius sensor script that i can assign and it works.
If you put the OnTriggerEvent method on your scanner it should run for every object it triggers I think, then in there you can individually check if that object is the one you want
nah i mean
i added an component via script
assigned to an variable
now i want to check if that collider that was collided with matches that var
or maybe tellme how to create an child gameobject via code?
you can google that part
but why can't you just access the parameter passed by the trigger collision message and compare that to the variable
is it possible to Attach to Unity using code?
I mean
if (Input.GetKeyDown(KeyCode.Space))
StartDebugging();
hello wise UDC, I come to you at a time of great need
I'm trying to figure out what would be the most optimal way to keep track of millions of different points on different bits of map geometry
the naiive answer would be to use particles, but research seems to show that Unity's particles are on the CPU and I'd be limited to ~50k
I'm looking into if shaders could potentially be more powerful but if anyone has suggestions / ideas I'd be extremely interested
explain what you mean by "keep track"?
You're talking about particles and shaders so maybe you're asking how to render something?
What are you trying to do?
Experimenting with a system where a sound will create a bunch of raycasts onto nearby geometry, and the points on nearby geometry that each ray hits have a glowing particle spawned there that lingers
This does kind of sound like a situation for gpu particles
you can shovel a very large number of world-space points into gpu memory
i was playing with a particle demo a friend made that did a million without too much trouble (purely gpu-simulated)
That's what I concluded from researching the topic, and I'm starting to re-learn shaders
A million would be ideal
i wonder if you could use the visual effect system
I found some easy solutions to it using HDRP, but I wanted to see if it was possible with URP
Would this be screen space shaders?
not really, since these are world-space points
What'd you do there?
vfx graph for sure
do you need to interact with these things?
it provides gpu particles, which are gonna be mandatory here
to be honest I'm still a little mystified by a lot of the VFX Graph system
I found a video of someone replicating a LiDAR effect, and I could def modify it for my purposes. It used the HDRP visual effect graph
the documentation is all over the place
proooobably not? Uncertain
looking into world space points ig
as in, positions in the world :p
that's all
X-space means "in the coordinate system of X"
oh,
I was under the impression shaders like
affected objects
as in they affect the shading of the faces of objects
didn't know that you could just go anywhere in the world
That's true for mesh renderers.
and I presume that even things like particles have some similarities
e.g. by slapping lots of quads all over the place
screen space shaders, for example, just draw a single big quad over your entire screen
I don't have a lot of experience with the more esoteric shaders, like what the Visual Effect system might use
Is there an easier way to set a GameObject to be a specific "type" of object other than Tags or a script with an Enum? I prefer the Enum route, but it feels a little excessive to attach a script to an object just so I can specify an Enum type.
Components can be small. That's what I'd do.
Remove the Start and Update methods and they won't get called by unity
('cos they won't exist)
Makes sense
the "enabled" checkbox should disappear from the component in the inspector
I know that shaders can produce geometry data. That's used for stuff like tessellation
(very confusing)
<-- confused ourplea
I guess the ideal "dot shader" would just have a huge list of vectors
for each one it'd make up a quad that's pointing at the viewer and render it
note that I am just guessing wildly here. i really need to learn this stuff myself...
You might wanna take this to #archived-shaders
ty! will ask
[System.Serializable]
public class Level
{
public string LevelName;
public List<BlockData> Objects;
}
[System.Serializable]
public class BlockData
{
public int BlockNumber, BlockType;
public float BlockX, BlockY, BlockZ, BlockValue, BlockValue2;
}
thislevel is Level
How can I make an "if" statement that checks if only x, y and z floats exist in the Objects inside thislevel
You need to define a float that is consider has not existing
Such as -1 or float.MinValue
^^ value type always exists
You could also use NAN I think
what would it mean for a level to have an object without a position?
There are 3 floats. their names are x, y and z
those values not existing doesn't seem reasonable. i wonder if there's a design issue here.
Probably like the size of the level
floats always start with default value cause its value type not ref type
hmm maybe you can use nullable floats
true, forget what i said lol
The player is able to possess any Entity in my game. Each Entity has a Brain. AI Brains are separate from player Brains.
Until now, I've only had one kind of player Brain. So, I just had a single PlayerBrain that was attached to whichever Entity was being possessed by the player at the moment.
However, each Entity has a specific player Brain that makes sense for it. Humanoids need the HumanoidPlayerBrain. Spectators just need a SpectatorBrain.
How should the Entity indicate which kind of Brain it wants? I see two options:
- Every Entity has its own instance of a playable Brain. That makes for lots of duplication, but I guess I can just prefab each kind of Brain.
- There is only one of each kind of Brain, all attached to a singleton. Entities need to be able to tell me which Brain they want.
The latter one feels better to me, but I remember this exact topic coming up yesterday
you can't really serialize a component type
I guess I can just have an enum.
Not the worst thing in the world.
It's a reasonably small set of Brain types.
okay, yes, that answers my own question ๐ฆ
does FindObjectOfType<T>() search for all additively loaded scenes, or only the active scene?
Factory Pattern
I guess I could construct a new Brain each time one is needed, too, yeah.
some Brains need special configuration (e.g. providing references to specific features of an Entity)
If you do not need anystate in your brain, then use SO.
Some have a lot of internal state.
Do you really need to change the brain of an enemy ?
well, there are two situations where that can happen
1: the player possesses them
2: some kind of effect replaces their Brain
like, imagine a "berserk" effect that just throws all of their AI out and makes them punch whoever's closest
That's actually working very well right now.
Seem to me that it is kinda complicated. Just modulate the behavior.
I suppose. I'll feel it out as I start adding some more content.
For the issue of reference, you would need to have a component that hold the reference for you.
And at that point, I wonder if you should just include the brain in the enemy directly.
And just swap whenever it is needed
In our game, we have BehaviorGraph that are instantiated SO. The data is hold on the Entity itself. I guess that would be more inline with the Factory approach
yeah.
the critical thing is that literally any of these solutions is wildly better than my old code
where every kind of entity had its own bespoke class and had separate blobs of code for player and non-player control
the enemy class was 2,200 lines long.
after pulling a lot of stuff out into a state machine
Oh... that is nothing
i'm sure you've seen worse :p
actually, only the original player class even let you control it
i thought about adding enemy control for a minute and then decided it's time for an overhaul
the player character behaved very differently when AI-controlled, since it let a NavMeshAgent set its position instead of using a rigidbody
notably, it would just...go through obstacles
I have the equivalent of 10k lines for the player through inheritance.
implementing everything twice was not fun
6k lines for the share behavior between a player and an enemy
from what i've tested only active scene
i need create an "if" statement that checks that "thislevel" exists in the Objects inside it, using only the x, y, and z floats
Terrible nightmare
i don't understand what that means.
thanks for doing the lord's work
I was just about to test it so you saved me some time
the documentation could really be more specific
yeah I also tried it with DDOL but still doesn't do it
it seems somewhat difficult to work with multiple scenes in general
unfortunately it's not something a lot of us can avoid :(
lots of teams seem to be using a multiscene workflow these days
yeah sadly, but there are ways. What do you need to do exactly?
instantiating some UI prefabs at runtime and using a game manager to sanity check all loaded scenes to make sure it doesn't exist anywhere else
why not store them in a list game manager holds of spawned UI stuff. Esp if its DDOL
not need to go searchin
that'll work actually, should be a lot faster than a bfs search lol
is a HashSet<myInterface> or generally HashSet<myClass a bad approach? I'm assuming it uses the reference to the object for the hashcode and not the data
wdym bad approach
like if the objects data completely changes that shouldnt affect the objects hashcode or the HashSet itself right
The reference is hash
Not the data
The size of an address
I'm wondering if its any worse to have a hashset of references vs a hashset of other data
well references are pointers so almost nothing
don't take this the wrong way but you sound like you're optimizing something that doesn't need optimizing
That would be 64bit on 64 processor 32 on 32 bit processor
its easiest to use a hashset to store thousands of object references and just use .contains instead of looping through it
I was just wondering if that was a bad choice but it seems pretty fine
the problem is the set will have counts in the 10-100k range in theory
so if I used lists and tried to compare two of them that could get slow
thx
A hashset or a dictionnary is the best data structure for this use case.
actually it worked on DDOL I think.. I just had to add a "delay" the scene loaded after the debug.log
god I love nondeterministic engines
you'll want to listen for the scene-loaded events
it was scene additive loading might be like async.
ikthere is LoadAsync Ig not sure how additive ran after second debug was ready or DDOL was too slow ๐คท
so it ran in the bg while the second debug.log ran first
IEnumerator Start()
{
DontDestroyOnLoad(gameObject);
Debug.Log(FindObjectsOfType<Tee>().Length);
SceneManager.LoadScene("scene2", LoadSceneMode.Additive);
yield return new WaitForSeconds(2);
Debug.Log(FindObjectsOfType<Tee>().Length);
}```
Trying to build for Linux, but clang seems to be against this idea
No less than four different error messages
All rather substantial
sorry so yeah using Async no need for delays ๐
nice to know it scans all loaded scenes, TIL
IEnumerator Start()
{
DontDestroyOnLoad(gameObject);
Debug.Log(FindObjectsOfType<Tee>().Length);
yield return SceneManager.LoadSceneAsync("scene2", LoadSceneMode.Additive);
Debug.Log(FindObjectsOfType<Tee>().Length);
}```
even though I've done my fair share of async code I never feel confident with it so I appreciate the effort from someone smarter than me lmao
nothing diffcult about async at all :p
specifically when you're writing "async" methods
i put that in air quotes 'cause it's going to be a unity coroutine
but close enough
in an async method, you're allowed to just wait for another async thing to complete
yeah bootleg async
since you won't block the main thread
i use true async when i do maui stuff
this does lead to a "turtles all the way down" problem
where calling async methods can only happen from async methods
fortunately, here, you just pitch it in a coroutine and call it a day
blessed be JOBS
i used jobs to do gradient-ascent for an RTS AI
nice and fast
i feel like i could batch up a bunch of these queries into some kind of horrific compute shader
maybe
Im trying to go full ecs but it gets complex quick for me
i've made one tech demo in (mostly) full ecs
way too complicated: making a sort of LOD system that would show a city in the distance
then show blocks, then buildings, then individual people, as you got closer
the next cities skyline ? :p
How long ago? Have you tried since 1.0? It's way more.... sensible now haha
This was right at the 1.0 release
actually, it might have been just before...
I remember following a tutorial that is no longer in the DOTS GitHub repo
lemme find that
Ah, here we are
I learned from this.
well, the "tanks" tutorial is still there; it's just formatted a lot differently now
it doesn't have as much verbosity in it
I think this was back when the official documentation was still very...sparse
As a pure hypothetical would it be smarter to perhaps create a decal or something instead of trying to use this godawful vfx graph
It does not feel like it was designed for this
ok so i need some help with something, imagine i had a box and on each point of the box and i have a dot in the center, when the top left box point is equal to one, the dot moves there, if the top left and bottom right are eqaul to one, it finds the average and puts the dot there, kinda like how a joystick works, if you dont understand i can ellaborate but i need help writing code for this, heres an image for reference.
basicaly when the mad value = 1 dot will be on bottom right, when it eqauls 0 dot will be in center
but the same for every corner point, and if more than 1 are equal to one, it finds the average
Can one of the four values be greater than 1? If no, then consider using bool values
hmm, I was going to say to give each emotion a coordinate and just add their (weighted) values
but that'd make the dot fly off the screen if you were mad and uh...tired?
Can be an option, 2 numbers ranging from -1 to 1, one per axis
I guess you could take the weighted average
Yeah. that'll work.
0.5 mad, 0.3 happy, 0.2 sad:
(0.5 * [1, -1] + 0.3 * [-1, -1] + 0.2 * [-1, 1])
0.5 + 0.3 + 0.2
with a special case for having no emotions at all
or just use a Vector2 and transform the dot locally around an empty game object at the center
Should my Camera, Audio Listener and Event Listener be marked as DontDestroyOnLoad() so I can have a single instance of each? Because right now I had one for each scene and am getting this in the console:
There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene.
There are 2 event systems in the scene. Please ensure there is always exactly one event system in the scene
are you additively loading scenes here?
Yes I am
Then you'll either need to make sure only one scene contains those components, or you'll want to DDOL them, yes.
that should be "and you'll want to DDOL them", no? because DDOL doesn't inherently prevent more than one of the same object, in fact it would just compound the issue as scenes are loaded and unloaded
I guess it depends on what's happening here
If it's one "main" scene with several other scenes you add and remove, then I'd just leave the camera in the main one
but if there isn't one main scene, then yeah, they should just live in that DontDestroyOnLoad scene
and even if you are doing the former, that strategy still works just fine
So if I decided to keep my main scene, with my Camera, Audio Listener, Event Listener and my different controllers.
And decided to load other scenes additively, marking them as DDOL would be useless?
And of course the different objects in the main scene would not be present in the other scenes and I'd have to figure out a way to get these objects from the main scene to my other scene after loading is complete.
Am I getting this right?
if you never unload that main scene, then yeah its pointless to mark those objects as DDOL. but if you additively load scenes and unload that "main" scene at some point but still plan to additively load those other scenes then yeah, you'd want those objects to be DDOL so they aren't destroyed when everything else in the main scene is
How can i make something like this or simlier to it
https://twitter.com/i/status/1680169229096476674
This is the video showing the game main mechanic character 1 (angel) move to the door, Then replay (the same moves that player gave to the game (inputs) ), Now the player play as the character 2 (devil) trying to kill the character 1 (angel)
Hey guys, hi, i'm looking for someone that can help with my code, its about steering behaviors, i'm trying doing my enemy AI script, basically avoid an obstacle, but im getting little stucked on it
{
Vector2 intention = Vector2.zero;
obstaclestocollide =
Physics2D.OverlapCircleAll(transform.position, radiusDetecObstacle, layerMask);
if (obstaclestocollide != null)
{
foreach (Collider2D obstacles in obstaclestocollide)
{
Vector2 directiontoObstacle
= obstacles.ClosestPoint(transform.position) - (Vector2)transform.position;
float distanceToObstacle = directiontoObstacle.magnitude;
float evadeForce = radiusDetecObstacle - distanceToObstacle / radiusDetecObstacle;
directiontoObstacle.Normalize();
rivalAIRB2D.velocity = rivalAISpeed * Time.deltaTime * directiontoObstacle * evadeForce;
}
}
}```]
just a second, i was drawing
the problem is, im not soo good with Vectors and stuffs
basically i don't how to calculate the trajectory
put it in code
like in the print a have the idea, but how to put it in action, i really can't see it
Your code for setting velocity is likely incorrect, Delta time doesn't make sense there.
Delta time is used for immediate moving, not setting speed
yes -- multiplying by deltaTime tells you how far you'd move in one frame
right, so i can remove it?
you should!
its a 2d game
velocity is how far you move per second
that's what the rigidbody expects
if you set the velocity to how far you'd move in one frame, then that's like dividing your velocity by the framerate
at 100 FPS, deltaTime is 0.01
so, it means velocity already apply the framerate?
If it's a vehicle you should consider using smoothlerp instead of abrupt changes in velocity
if the velocity is Vector2.right, the rigidbody will move to the right at 1 m/s
And deltatime is often (1 / 60) = 0.016777.
Meaning your final speed was being multiplied by a very small number
indeed
its not a vehicle, its a rpg topdown character, and my next step is implement a avoidance in the 8 direction of move
okay, so if i remove the deltaTime, my movement will be a lot more precise
not "more precise"
I guess it is going to be correct, instead of wrong
Set the velocity to how quickly the rigidbody should be moving
right
More like "not near 0"
okay
This is very helpful for pathfinding
i really like the ideia, but im trying to implement my own codes, cuz i want design a lot of behaviors to my enemys
to bring life to it
You put your code on top of a existing navmesh framework
Navmesh will merely help you calculate those directions
Nothing stops you from "bringing life" to it
yeah, you can prevent the NavMeshAgent from actually moving
and then just ask it how it wants to move
i know, but i really apreciate code all this thing, but of course, if i get tired, i'll give up, and go to navmesh
i understand wanting to do it from scratch. It's very helpful in learning too. However what you're asking for help on is not a very easy task if you're doing it from scratch. What you may be able to do is get the vector from the enemy to the player, then raycast along that and if it hits something start rotating that vector left or right (probably both at once) and when it stops hitting something move in that direction, but keep trying to rotate it back towards the player.
although that alone could get stuck in areas pretty easily
You're basically going to have to code your own navmesh them, otherwise your agents will likely get stuck at many different situations, consider searching about a step by step process of coding a navmesh framework
exactly what i think, but the math inside Vectors let me confuse, and i dont how to use the idea in the code
"you may be able to do is get the vector from the enemy to the player, then raycast along that and if it hits something start rotating" how
?
you could combine the A* algorithm with this vector idea and basically eliminate the directions that lead to dead ends.
like avoid = obstacledirection - enemypos;
if you're having a hard time understanding the vector math required, perhaps it's time to read up on it or use navmesh:
https://www.youtube.com/watch?v=MOYiVLEnhrw
Welcome to my four part lecture on essential math for game developers ๐ I hope you'll find this useful in your game dev journey!
This course will have assignments throughout, if you want to maximize your learning, I recommend doing them!
If you are enjoying this series, please consider supporting me on Patreon!
๐งก https://www.patreon.com/acegik...
thanks a lot, i should think in tutorials in addition to simple copy and paste other videos tutorials
you can also rotate vectors using quaternions but that's a whole other mess, but luckily unity has some things like Quaternion.AngleAxis to help.
i came here just to know how to make a simple line of code, but now i see i was lazy
i believe so, cuz it can rotate to ever ahahahha
thanks to all
yea, pathfinding is a pretty big thing. However if your game is simple enough you can probably just say start moving at 45 degrees when there's an obstacle in front
for example if it was a sidescroller with an enemy chasing you or something, then that would possibly work
Can someone take a look , I dont understand why enemy is not stopping
You're accessing the wrong variable inside the coroutine, it should be enemyscript.Get**()
You didn't assign "EnemyMovement" anywhere, it should even be throwing a null reference exception
In fact almost everyline there can throw an exception
This will return null if no component was found
other.gameObject.GetComponent<EnemyMovement>()
yeah i tried that and the dot flew off screen
wait will this work?
ok lemme try it
(you could prevent this by adding a tiny constant term to the denominator)
or by just having a special case
I still think it's easier to just move the dot relative to a transform at the middle of the scale with a vector2
Hey, I'm sure this is a really simple question, but how do I reference a C# script in another script. I am making a card game and I want a Card class to be referenced and used in a manager scripts. The only way I have found to do that online is to grab the reference from an object, but I don't have the script attached to objects; instead, want to use the class itself within another script. How can I do this?
ideally, you just declare the name of the Class and reference via inspector
[SerializeField] YourClassname yourClassname; << assign via inspector per drag drop
then use it inside of your script with
yourClassname.someVariable
Do you understand the difference between a class and an instance of a class?
Also is your class that you want to reference a Monobehaviour or not?
No it's not a monobehaviour
yeah
Do you want it serialized in the inspector?
If not you can just make an instance with new
Like a normal C# class
That makes sense... I was assuming there was a way to make an import style statement at the top
The using things at the top are just convenience so you don't have to write the whole fully qualified name of the class
They don't do anything besides that
E.g. you can write GameObject instead of the full name which is UnityEngine.GameObject
How do i reference the TextMeshPro text type in a script? I was following a tutorial for a game, but they use just "Text" objects and not "Text- TextMeshPro" , then they declare some variables to drag and drop said items in the editor.
public Text currentHealthText;
But when i went to do that, i cannot drag and drop them into the editor?, my guess is that it has to do with the type Text being different than the actual game Objects i'm using, so, how do i set the type correctly?
TMP_Text
You need to use the TMPro namespace, yeah
well here ill send my code and you judge
i try to average them out but it makes the dot go off screen
please paste your class code here, if it has serializable fields, you can put the [System.Serializable] attribute on the class and you'll be able to edit it in the inspector
actually i have an idea, ill just set the Y or X value of the dot equal to the perimitor of the box if it goes outside of it
not a very good idea I don't think
since you posted a screenshot it's hard for me to read it and type at the same time
but u can use a Vector2 to tell it up/down/left/right by setting the x/y component of the vector to a value between -1 and 1 for both, then you can multiply both the x and y by half the length of the square.
yeah didnt work
what?
it didnt work the thing i tried
try this
mk
to get half the length of your square multiply the x or y size by the scale then divide by 2
actually its kinda hard to understand, could you send code lol?
if not ill figure it out ig
which part is hard to understand? I know I did not explain it very thouroughly.
use a vector2 on the point that moves? and set it equal to what?
so your vector2 has an x and y component. the x and y component will be each individually expect a value of -1 to 1, -1 being all the way left/down and 1 being all the way right/up.
cause how it works rn, is i have floats for each corner that change depending on the value, and then i add them together and find the average then thats the position of the dot, but that makes it fly out of the sqaure if more than 1 of the floats is more than 0
you would then multiply that vector by half the size of your square, and set the gameobject's local position to that value.
this would work for all 4 corners?
whats gonna tell the vector what value i want tho
you are
yeah i get that
with... variables?
do you have some way to track how happy/sad/afraid/mad something is?
thats kinda already what i have, but im just averaging the numbers instead
make a variable for happy/sad that is a float, and limit it to a range of [-1, 1].
then make a variable for mad/afraid and limit it to a range of [-1, 1].
yeah i did that
hold on
how do i send code again?
sorry wrote that wrong, give me one second
k
you probably want to use Vector2.Lerp here.
This is very untested, I'm literally writing it in discord, it could be something like this:
float happySad = 0; // value is from 0 to 1
float madScare = 0; // value is from 0 to 1
Vector2 position = Vector2.zero;
Vector2 first = Vector2.Lerp(new Vector2 (-1,1), new Vector2(1, -1), Mathf.Clamp01(happySad));
Vector2 second = Vector2.Lerp(new Vector2(-1, -1), new Vector2(1, 1), Mathf.Clamp01(madScare))
position = (first + second) / 2;
dude there's a clamp function lmao
id like happy sad mad and scared to be there own floats
idk how to use it ๐ฅธ
Mathf.Clamp(numberToClamp, min, max);
what does it do
it clamps the number to or between the min and max
ohhhhh
if less than min, it returns the min number. if more than max, returns the max number. otherwise, return the number supplied.
yeahhh thats a lot easier
is there a reason?
cause there gonna be there own functions in the game im working on, and eventually im gonna replace these floats with statics or something
but here:
float happy = 0; // value is from 0 to 1
float sad = 0;
float mad = 0; // value is from 0 to 1
float scared = 0;
Vector2 position = Vector2.zero;
Vector2 first = Vector2.Lerp(new Vector2 (-1,1), new Vector2(1, -1), Mathf.Clamp01((happy + sad) / 2));
Vector2 second = Vector2.Lerp(new Vector2(-1, -1), new Vector2(1, 1), Mathf.Clamp01((mad + scared) / 2))
position = (first + second) / 2;
lemme see if that works
yes because I don't have unity open
remember, set the dot's local position to the position value
and make sure its parented to the square or whatever has an origin point at the center
for some reason
it makes the dots positionX negative 1 when i play it
but it seems to work? maybe?
besides that
can u add a debug log statement to log what the local position is after setting it, and what first is, and what second is?
yeah hold on
first vector is the local position, second is first, and third is second
weird.... ๐ค
any idea?..
all your happy/sad/mad/scared values are 0?
i know the problem is with the happy/sad/mad/scared values being seperated. Can you try it again with them being exclusive like originally stated? then default of 0.5 would be in the center.
pretty sure that would work, and it's more clear to have the emotions tied to one variable if they're eclusive.
yes
just try this, pretty confident it would work then
so make 4 variables instead of 2
make 2 variables instead of 4 you mean?
i dont really want it like that tho
well once it works like that then figure out how to split it into 4
because they HAVE to be tied to each other regardless, so it makes sense for it to be like that. There's no way to have both 1 on happy and 1 on sad.
well if you did it would be inbetween the two
in the middle
ok try this then
really the dot needs to be closest to whichever value is higher but also pulled back by the other values
just a negative in front of happy and mad
ok
but then the problem is the lerp, don't do that actually
just try with the 2 variable thing. If it works, there, figure out how to split into 4
yeah it didnt work cause they had to be negative for it to move
k
its still -1 over on the x
with both values 0.5?
yes
now how do i make that work in 4 directions tho
why doesn't it work in 4 directions now?
well its the exact same as the setup before but with two directions
so why would it be differnt now if i added 2 more
so if you set one value to 0.25 and one to 0.6, what happens?
with the two setup or 4?
with the two setup
this is pretty easy
this just seems overly complicated
it worked fine with the 4 thing besides it being -1 over on the x
This is not what I suggested.
You should do a weighted average of each emotion
yeah thats what i was thinking to average them out, but idk the right way to do it
Assign each emotion a position. They will probably be [0,0] to [1,1] or [-1,-1] to [1,1]
yeah thats how i originally had it
Multiply each position by its weight, then sum those up
Then divide by the sum of the weights
Hey! is there any way I can improve my dash? It's a little clunky
void OnRoll(InputValue value)
{
// Input handling and movement
if (!isAlive) { return; }
if (!rb2d.IsTouchingLayers(LayerMask.GetMask("Ground"))) { return; }
float moveInput = Input.GetAxis("Horizontal"); // Get input from the player
if (Mathf.Abs(moveInput) > 0.1f)
{
if (_canRoll)
{
_isRolling = true;
_canRoll = false;
trailRenderer.emitting = true;
animator.SetTrigger("Rolling");
FlipSprite();
StartCoroutine(StopRolling());
}
if (_isRolling)
{
rb2d.velocity = rollingDirection.normalized * _rollingVelocity;
return;
}
if (cc2d_Body.IsTouchingLayers(LayerMask.GetMask("Ground")))
{
_canRoll = true;
}
}
}
private IEnumerator ResetRollingAnimation()
{
// Wait for a certain duration
yield return new WaitForSeconds(0.5f); // Adjust the duration as needed
// Reset the "Rolling" trigger to transition out of the animation
animator.ResetTrigger("Rolling");
}
private IEnumerator StopRolling()
{
yield return new WaitForSeconds(_rollTime);
trailRenderer.emitting = false;
_isRolling = false;
}```
wdym by "weight"
If madness is at 0.5, the weight is 0.5
ah
again, see the linked example
This will give you a point whose position is based on the balance between the four emotions
my solution also will if you just have 2 variables instead of 4 :p
thats whats i had orginally but if more than 1 emotion was = 1 the object flew out of the box
Not if you were averaging them correctly.
You must divide by the sum of all weights
so add all of them then divide by 4 right?
No.
.
If all four emotions are at 50%, then each one has a weight of 0.5
So you would sum up the following:
yeah
0.5 * [1,1] + 0.5 * [1,-1] + 0.5 * [-1,1] + 0.5 * [-1,-1]
Then you would divide by
0.5 + 0.5 + 0.5 + 0.5
In this case, you'd get [0,0] divided by 2
Suppose we had 100% weight on the [1,1] and [1,-1] emotions
[1,1] + [1,-1] = [2,0]
[2,0] / (1 + 1) = [2,0] / 2 = [1,0]
so multiply each emotion by its position, then divide it by each ones value added to each other
Right.
oook lemme try
Also, if the sum of weights is zero, just put the dot at [0,0]
Since you'll otherwise have a division by zero.
yes, the other scheme would be to figure out two underlying feelings that produce the four emotions
maybe happiness and energy or something
happy + energetic = excited
unhappy + energetic = mad
happy + unergetic = tired
unhappy + unenergetic = sad
that would be a different system entirely, though
yeah
but right now happiness is exclusive to sadness so just say if 0, happy, if 0.5, neutral, if 1, sad
i just want the average positon based on each ones value
yeah
its kinda like how joysticks work
what i want i mean
If you want to visualize four completely separate emotions, then you'll get some ambiguous results
if the dot is at the middle, that could be any balanced amount of all four emotions
yeah i know thats how i want it
i got this error
dividing by 0 or a really tiny number probably
oh i gotta make the 0 function
right
no you don't
yeah that
you can do, no extra function needed
if(denominator == 0)
// dot at 0.5, 0.5
else
// calculate
well, unless you wrapped the rest of your code in an else down there
you're still trying to assign a bogus position to your transform.position
that triggers the error instantly
ahhhh
dh
duh
i think it works? maybe?
well, are you actually doing anything with EmotionAverage?
it seems to me like you should do
emotionSum = MadAmount + ...
Vector2 target;
if (emotionSum < 0.001f)
{
target = Vector2.zero;
}
else
{
Vector2 positionSum = MadAmount * MadVector + ...
target = positionSum / emotionSum;
}
EmotionDot.transform.position = target;
note that you can multiply a float with a Vector2
it works!
the dots positon = emotion average
yes. i noticed you were constructing a new Vector3 from individual components there
you don't have to do that
you can just multiply MadAmount with MadVector
well the average is a vector3 and i just put 0 for z
yes. you can still just multiply MadAmount with MadVector
it works but theres a bug idk how
Vector2 can implicitly convert to Vector3
so you mean? in a vector2
Yes.
i tried that and it didnt work for some reason lemme try again
i don't see what the problem is
ah it works now
when all the values are = 0 the dots pos != 0,0
show your current code
https://gdl.space/utehayowag.cs keep in mind im gonna fix the values being clamped to 0 - 1.5 eventually
to make it less spaghetti code
and I see a problem with my scheme now
so the idea is that the mad vector would just be [1,1]
so that if you were 100% mad, you'd be at [1,1]
(with no other emotions)
but the weighted average causes a problem here
suppose you're just 10% mad with no other feelings
0.1 * [1,1] = [0.1, 0.1]
but then you'd divide by 0.1 and be at [1,1]
actually, question:
suppose you were 50% mad and 50% happy
Where would you want the dot to be?
I see two reasonable locations:
- halfway to the bottom
- all the way at the bottom
actually, giving it some more thought, I think this IS reasonable. Making each vector depend on the strength of the emotion means the dot gets positioned right!
Your problem is that you don't update EmotionAverage if all of the emotions are at 0%
You set EmotionDot.transform.position, but then EmotionDotLocation() runs and sets the position again
So just make line 112 set EmotionAverage to Vector2.zero.
yeah, that's all correct, then.
true
uhh soo i need to update emotion average if all emotions = 0
Right. Your code currently sets the transform, but that gets clobbered immediately when you call EmotionDotLocation
So just set the average to zero if the emotion sum is zero
ok
i think this shouuuld work???
No, that doesn't fix it.
oh
If the sum is zero
set the average to Vector2.zero
ah
This checks if the average is zero and...sets it zero again
fixed??
Where is this code?
i replaced the EmotionDotLocation() with this
My suggestion was to change one line in setVectors
if (MadAmount + SadAmount + HappyAmount + ScaredAmount == 0)
{
EmotionDot.transform.position = new Vector2(0, 0);
}
else
{
EmotionAverage = ...
}
This should just set EmotionAverage to Vector2.zero
that's it
yeah
wait why are you not setting emotiondot = to emotion average? is it assumed its done elsewhere?
this makes more sense to me
seems to fix the issue tho!
looks like it works now ๐
thanks to everyone who helped me ๐
well, you have that separate method that does it
but it is more reasonable to just do it right away
yeah i moved it over
so if I have vector v and i put it in a pure quaternion V, should i just chop off the real part of V' = QVQ^-1 to get v' ?
i don't understand what you're asking
are you asking about manually performing a rotation?
Why would you put a vector in a quaternion?
because Q * V * Q^-1 does remind me of how that works
yeah
i read that vectors can be represented as quaternions with no real part, so that you can do quaternion maths with them, but nobody ever told me how to get the vector back lol
w is the real part, right?
yeah
i'll do quaternion maths by hand at some point
pain ^
but yes, I believe you take the products and then just lop off the real part
mildly confused by the notation: i'm seeing people write quaternions at [w x y z] when showing the math
that does match how you write a complex number
a + bi
yeah, took me a few fails to realize that w goes on the end in unity lol
If you just multiply a vector by quaternion in the right order, you should get a rotated vector.
yeah, Unity does that for you
Quaternion * Vector3
pentagon here is asking about doing the math by hand
Like on paper?
well, on the computer, just without Unity doing it for you
you just do some Hamiltonian products (multiply the two quaternions with the distributive property)
hey, that sounds remarkably easy...
yeah was just trying to get a more fundamental understanding of them
this is cute tho, i didn't know this operator existed
yeah, that's how you're meant to use them in unity :p
oh yeah, and if you hit F12 to view how the * operator works, it does more-or-less exactly what's depicted in the above image
how do rigidbodies move internally?
Im trying to do something involving mesh colliders on rigidbodies (which dont go obviously) as a test
my approach is proxy colliders
but when I move a proxy collider to the position of a rigdbody its far from perfect and jumps all over the place
this code works much better but it still has small artifacts (rigidbodies sitting on it still jump around)
coll being the target rigidbody (misnomer i know)
whats the best approach for this
Internally like in the physics representation or what you actually see in the game?
Assuming you mean the physics representation, their position is updated each fixed update based on their velocity. The transform and the rigidbody positions are not the same thing. The rb position is synced to the transform at some point. If interpolation is enabled, then it's definitely in update, since it needs to interpolate between last and next fixed position. If interpolation is not enabled, I'm not sure, but I'd assume it's in update as well.
yeah how would I make a proxy collider follow it then
should I use rb.position somewhere
Just setting it to the same position as an rb in update should work imho.
Though, I'm not sure if that updates the position of the collider in the physics world.
I don't think there's a need to use rb position, since it would be the same as transform position in update if I get it right.
I guess it would not be the same position in case of interpolation.
Generally, I'd avoid moving non convex mesh colliders at all...
I always say that if your implementation is fighting the engine, then you're doing something wrong and there's probably a simpler way compatible with the engine.
Any one know how to extract a mesh's submesh to be its own individual mesh
i cant figure it out because if i extract the slice of vertices the triangles wont have the correct indices anymore
so its a bit of a messy problem
Mesh.GetIndices(int submesh) should get you an array of the submesh indices.
Is there any problem with using that?๐ค
No that's fine but the triangle indices won't start at the right place
Wdym by that?
Well i also need the tris array to go with it that correctly point to the right vertex index
Since they point to their position in the original mesh
Indices are the tris. You get a sequence of 3 indices that make up a triangle.
Well yes, they point to the mesh vertex buffer/array.
Right but my new mesh the verts start at 0 not where the submesh started
If you need to split that into separate buffers, you'll need to extract them and recalculate the indices.
That sounds complicated
There is applyBaseVertex flag, probably what you want?
In Mesh.GetIndices. Default is true so youโd want to set it false
What's the difference to that and get triangles function
Should do same thing if your mesh topology is triangle
i dont follow what that means i would assume all indices follow triangle topology for meshes
Not necessarily, you could make mesh with Quad topology , etc
Though not much used
i see
ill try it
last time i attempted this i had out of bounds errors
which was odd
is there no get vertices per submesh ?
or will i have to do that manually
Well submeshes can share vertex buffer
ah true
so it cant even be guarenteed the vertices will be all sequentially together in the mesh to extract?
Thatโs why applyBaseVertex is true by default
You canโt really guarantee and they could overlap yeah
because i was thinking of using array slice with baseVertex + vertexCount
that sounds like a tricky problem then
what is the usecase for this, like if its a mesh you built in code you can control this stuff
if not, why not fix it in a 3d package first
Yeah depends on how your mesh formed
im copy pasting the mesh along a path and want to make it one single mesh
so i want to combine each similar submesh together
so for doing a mesh along a path, i would literlaly just use a ring of verts
like just the profile
huh
and build it all out in code
but that is assuming you want to bend it along the curve
I mean base vertex + count would have all vertices that submesh uses
But plus possibly unused vertices
And removing them would be pain ๐
Shifts index around
this is what im trying to do on the right
each colour represents a submesh
what unity does is the left if i just copy paste and combine
it creates tons of submeshes
this is 4 of the same mesh copy pasted along a line for example
Are you using Mesh.CombineMeshes?
so what im thinking is get the submeshes individually as a mesh and copy paste them along the line then combine that submesh ... do that for each submesh then finally combine those combines to the final mesh
There is flag too, mergeSubMeshes ๐ค
yeh then i lose ALL submeshes so i would only have 1 submesh
theres no "preserve like submeshes" kinda option
why is that so important
because they have different materials
because they each one has to be a gameobject
Combine submeshes that uses same materials first each
Then make final mesh with those ?
exactly but to do that i have to extract each submesh
which was why i was asking about how to get the vertices correctly
but why provide it as a mesh with 2 sub meshes
You can set submeshIndex in CombineInstance
So are these original meshes external assets?
then combine again
its a tool that suppose to work for any mesh provided
yes
So you can cherry pick what submesh you wanna combine
By material
Repeat per material then combine as final mesh preserving submesh
in order to combine submeshes i first need to extract the submesh data
to lerp along the path
I mean, you could go over each submesh and create a triangle struct for each triangle holding 3 vertices. Then just use these triangles collection to create a new mesh...
feels its being over thinked
thats not how the submesh combine works though
like do everyting twice then a final combine that does not merge submeshes
Does anybody have any idea why I can do this:
_material = _renderer.material;
I am aware that renderer.material creates a new instanced material and assigns it to the renderer at this point, then I cache it in _material. However, later I try _material.SetColor and it does not affect the renderer? Upon debugging I see that the renderer's material says (Instanced), but the instance ID does not match the one I see in _material in the debugger. So modifying _material is modifying it, but it's not the material on the renderer for some reason. I don't know the reason.
I've put a conditional breakpoint in Renderer.material's setter and have confirmed that nothing else is assigning to the material on this renderer.
this was my original attempt:
for (int s = 0; s < submeshes; s++)
{
var tempMesh = Object.Instantiate(mesh);
var submesh = mesh.GetSubMesh(s);
Debug.Log("Submesh: " + (s + 1));
Debug.Log("Triangles => From: " + submesh.indexStart + " to " + (submesh.indexStart + submesh.indexCount));
Debug.Log("Vertices => From: " + submesh.firstVertex + " to " + (submesh.firstVertex + submesh.vertexCount));
int[] tris = mesh.triangles[submesh.indexStart..(submesh.indexStart + submesh.indexCount)];
Vector3[] verts = mesh.vertices[submesh.firstVertex..(submesh.firstVertex + submesh.vertexCount)];
Vector3[] newVerts = new Vector3[submesh.vertexCount * ((int)path.Length + 1)];
int[] newTris = new int[submesh.indexCount * ((int)path.Length + 1)];
for (int i = 0; i < path.Length; i++)
{
int triIndex = i * submesh.indexCount;
int vertIndex = i * submesh.vertexCount;
var t = i / path.Length;
for (var v = 0; v < verts.Length; v++)
{
var time = t + range * verts[v].z;
var p = path.Lerp(time);
newVerts[vertIndex + v] = p;
}
for (int tri = 0; tri < tris.Length; tri++)
newTris[triIndex + tri] = tris[tri] + submesh.vertexCount * i;
}
tempMesh.vertices = newVerts;
tempMesh.triangles = newTris;
tempMesh.RecalculateNormals();
tempMesh.RecalculateBounds();
combines.Add(new() { mesh = tempMesh });
}
but it was a big flop
Wdym, thatโs Unity API
Just accessing the property probably creates a new material instance that is assigned.๐ค
Try shared material instead.
the issue it either considered each combine a submesh OR you merge all combines to one submesh so you end up with only one submesh at the end
i would be tempted to just explicitly make your material with the copy constructor from the shared material
then assign it back to material and cache it
thats what i was assuming i would have to do -_-
what a pain!
Cherry pick and aggregate your submeshes first
combines.Add(new() { mesh = mesh, submeshIndex = s })
also have to make sure when i do that the verts are in the right place
Then combine those combined submeshes
yes but i cant do that until i can get an exact copy of the verts to paste along the path anyway
WHY
wdym why
the mesh you add to the combine would need to be containing the info of the specific submesh not the whole object
You donโt even need vertices with this
๐ค i dont follow
Just use original mesh + submesh index
Then combine will take info from that submesh
I don't want shared material because I don't want to affect every single one of these renderers, just this one.
but im creating more mesh data along the path
maybe im not following the logic
material has a copy constructor, could use that to create your new instance from shared, cache that to a field, that assign it back .material
Thatโd be separate concern?
You can preprocess that
Then combine however you want
I tried this and it has the same symptoms / problem.
strange, normally how i handle it or just caching .material from the start
normally would ask you to breakpoint and ensure its not being set again by something else
but you said you did that already
Must be doing something wrong then. Share the code when you attempt that.
What kind of material are you using?
which renderer are you in?
let me try modify my code for it can i ping you when ive done it assuming it doesn't work to see where im going wrong
If the material is not working properly, setcolor won't work as well
Yeah I breakpointed in .material's setter with a conditional breakpoint that logs a stack trace, it only gets assigned once.
MeshRenderer
What is the material?
also what are you calling to set props
some things only work if the shader has the correct property names
also could there be a material propertly block overriding ?
_material = new Material(_renderer.sharedMaterial);
_renderer.material = _material;
...
_material.SetColor(Color.red);
(Color stays black).
No property blocks, I'm actually trying to migrate away from those now that I'm on the SRP batcher.
Trying to figure out what the new workflow is. It's a shader graph.
Can you inspect the referenced material in the inspector? Does it change color?
is the property exposed in the shader graph?
show us the graph
Yeah I've been looking at it, it does not change color. Yes the property is exposed.
what is the prop named?
The problem is pretty certainly that _renderer.material and _material have different instance IDs so I'm setting the color on a totally different material somewhere. I'm just not sure why assigning a material doesn't...assign the material.
don't you need to pass a property id here? _material.SetColor(Color.red)
Yeah, sorry that was pseudo code.
but you are acccess .material again to check its id
Calling .material makes sure there is a new instance assigned to the renderer
thus creating a new one
only ever do .material once to set or get it
then use the cached one only
That part so gross
Yeah I only do it once, I'm comparing the ID of _material, not renderer.material, to the material I see in the inspector.
That contradicts what you said earlier about it not changing in the inspector(the _material one)
also ensure you are setting it on the real name or id of the prop not the pretty name
Yeah I'm using the reference.
Tbh we will be making shots in the dark, as long as you don't show us the actual code/graph
I've set colors many times with MaterialPropertyBlocks, just trying to figure out how instanced renderers work in the SRP batcher.
The problem isn't anything with the shader graph or how I'm interacting with it, it's that there are two materials, one I'm caching, and another one coming from somewhere on the renderer.
but you are hitting problems and cant finding them with that reasoning
There shouldn't be any difference with working with materials between render pipelines.
so test all assumptions
Aside from properly names maybe
is a bit actually MaterialPropertyBlocks dont batch in srp
Yeah, but I'm not referring to MaterialPropertyBlocks. Just getting, setting and editing the materials themselves.
yeah that all works indentically
since all the time so i can get things to batch i will make runtime instances of things with common props and assign them all to renderers
Hey everyone, I'm here looking for suggestions, I want to integrate AI into my FPS game, I want to create behaviors like patrol, attack, attack force, and alert state behaviors, but especially the behaviors I've been working on are cover behaviors. , and behavior of flanking the player, but I feel that everything has been getting more and more complicated for me, I want to know if you can recommend any asset from the Unity Asset Store that will help me with the basic behaviors but that will allow me to create my own advanced behaviors.
At the moment, the ones that I have seen that are closest to what I want are these two assets "Invector FSM AI Template" and "Behavior Designer - Behavior Trees for Everyone", if someone has used them and can tell me which of the two I want can help me meet my goal of advanced behaviors without using ML, or if you can recommend me a new one please.
ok didnt work but maybe i dont understand the final part because it made multiple submeshes like what happened the first time i tried:
if i set to true
then all submeshes get merged which is equally not what i want
because the original mesh had 2 submeshes
so the final result should have 2 submeshes aswell
How are you calling CombineMeshes now?
let me post it in a thread
None, Unity assets that are code related will hinder your learning progress and give you headache in the future (a lot of them have bugs that require you diving into their source code to fix)
What I can recommend is taking some time to study StateMachines, and how experienced developers make them
That's a bit of a radical view. I was thinking the same earlier, but I came to appreciate preexisting assets/code.
The only Unity Code asset I trust is Dottween, and I have already seen a good share of bugs/undocumented behaviour on that one.
Radical != incorrect
If it's open source or has a clear documentation I think it's totally worth the time saving.
Most open source ones I found were poorly maintained, which lead me to go bug fixing myself, when I could have spent less time making the thing from scratch
And also improving my code skills on the process
That's very questionable. You'd probably spend close to the same time debugging your own code.
There's a reason why we buy things from other people instead of making them from scratch. The same applies to software components.
It's debatable, sure. Depends a lot on the size of the code we are talking about.
But even if I spend the same amount of time debugging my code, I'll still learn more
There's a difference between a team of engineers with funding vs random person on the internet
I find that I can learn a lot of new things looking at other people code rather than my own.
Yeah the random person on the internet has passion for what they do. ๐
Yes. But you have the privilege of only buying an asset that satisfies your standards.
Until they don't, and stop maintaining the project
That's a pretty wide generalization though.
I completely agree, but you will learn a lot more if you analyse someone else's code then make your own implementation vs just downloading the package
I don't get how this is relevant
I've been working with Unity for over ten years and I still grab assets, they save you from having to write a bunch of boilerplate stuff so you can just make your game.
Unless you want a bug free game
There is no such thing as a bug free game.
there absolutely is
It's relevant because you can decide whether the specific asset is worth using vs implementing the feature from scratch yourself.
There isn't a bug free game. It's statistically unlikely.
You can argue all you want about the semantics of bug free, but on the eyes of the player if he never saw a bug then it's bug free
Anyways, the point is: you should decide for yourself wether it's worth buying an asset or not. We provided the pros and cons, but ultimately it's a matter of preference.
Wow just realised the award thing is on! Happy for all those people that made it and the people who helped! โค๏ธhugs
Bye ( looks like a fun concert ๐คฃ๐คฃ) ๐คท๐ป
This is a kind of niche question and I'm really struggling here, but how can I modify the submesh indexes of an imported mesh?
Re-order them, I figured it'd be an import setting or something
So, I'm making destructible props, and the way I'm doing it is by creating a particle effect that takes submesh 0 (because it can only handle one submesh) and creates a particle based off it
Problem is, I don't understand how Unity determines what index 0 is
Submesh data contains the index offset.
You can get the sumbmesh index offset from the Mesh API
I can tell easily enough which submesh is assigned to what index, but that information isn't useful because I need to create a standard
Otherwise I'd need to check every mesh for every prop in the game, and manually set which submesh index is the important one
If I could just set the important submesh to be index 0, that'd simplify it a lot
Do you happen to know how Unity determines which submesh is index 0? Or does that info come from the file itself?
It doesn't seem to be determined by material order, or by vertex count
Probably comes from the file itself. It's decided when the mesh is created.
If you want to standardize it, you'd need to tell that to your 3d designers, or edit the mesh in 3d software manually.
I understand how to make a state machine, I'm just looking for a plugin that makes it easier for me not to reinvent the wheel, I try to keep my development as efficient as possible without reinventing what already exists, although I understand what you mean but I can't stop thinking In the large amount of work that I can save if I use a tool that can help me, really in the Active Store there are many professionals who are perhaps doing things better than me.
Why do people use an 'Orientation' gameobject to store their character controller's rotation?
Why not just rotate the parent gameobject?
Because they all watched the same tutorial that does that๐คทโโ๏ธ
Well, you don't notice it if you copy paste the code and the tutorial as is without understanding it.
wait till you notice all the people multiplying mouse movement by deltaTime
Thanks brackey
So setting transform.position on a parent game object doesn't move children object colliders ๐
Does anyone know how to workaround this?
lol rip
so im currently trying to figure out some asynchronous code
if i call an async Task SlowFunction() from a void without awaiting it should run without holding up the program correct?
yes
It should move colliders. Unless they're static(in which case they shouldn't move anyway) or have a dynamic rb(in which case they shouldn't follow the parent anyway).
they're neither of those :\
Weird thing is, if I do something that changes the way it functions, it does update to the new 'last' position..
ie add rb to child and remove it
ah, is there any reasons why it wouldn't do that? as currently the Task seems to run synchronously causing a 14s lagspike
yeah there is definitely some fuckery going on
Can't really help you without more details.
pretty much all I'm doing is transform.position setting every update on a gameobject to follow the player
Share the code of the task.
Ok, so how do you find out that it doesn't update the position?
I will send clip hold on
it gets metadata from mp3 files (im making my own music player)
async Task ReloadAllSongs(){
Debug.Log("Reloading all songs");
DateTime start = DateTime.Now;
//reload all songs
songs.Clear();
FileSuper fs = new FileSuper("AirPlayer", "ReplayStudios");
char [] invalidChars = Path.GetInvalidFileNameChars();
Save save;
TagLib.File tagFile;
for(int i = 0; i < paths.Count; i++){
string[] files = Directory.GetFiles(paths[i], "*.mp3", SearchOption.AllDirectories);
for(int j = 0; j < files.Length; j++){
try{
Song song = new Song(files[j]);
tagFile = TagLib.File.Create(files[j]);
song.name = tagFile.Tag.Title;
song.artist = tagFile.Tag.FirstPerformer;
song.album = tagFile.Tag.Album;
song.albumArtist = tagFile.Tag.FirstAlbumArtist;
song.art = PlsImage(tagFile.Tag.Pictures[0]);
string safeName = song.name; //filter to only letters and numbers and spaces
foreach(char c in invalidChars){
safeName = safeName.Replace(c.ToString(), "");
}
save = await fs.LoadFile($"songData\\{safeName}.dat");
if(save != null){
song.playcount = (int)save.GetInt("playcount");
song.rating = (int)save.GetInt("rating");
song.dateAdded = DateTime.FromBinary(long.Parse(save.GetString("dateAdded")));
song.lastPlayed = DateTime.FromBinary(long.Parse(save.GetString("lastPlayed")));
song.lastSkipped = DateTime.FromBinary(long.Parse(save.GetString("lastSkipped")));
}
else{
song.playcount = 0;
song.rating = 0;
song.dateAdded = DateTime.Now;
song.lastPlayed = DateTime.Now;
song.lastSkipped = DateTime.Now;
save = new Save();
save.SetInt("playcount", song.playcount);
save.SetInt("rating", song.rating);
save.SetString("dateAdded", song.dateAdded.ToBinary().ToString());
save.SetString("lastPlayed", song.lastPlayed.ToBinary().ToString());
save.SetString("lastSkipped", song.lastSkipped.ToBinary().ToString());
await fs.SaveFile($"songData\\{safeName}.dat", save);
}
tagFile.Dispose();
songs.Add(song);
Debug.Log($"Loaded {song.name} by {song.artist}");
}
catch(Exception e){
Debug.LogError(e);
continue;
}
}
}
DateTime end = DateTime.Now;
Debug.Log($"Loaded {songs.Count} songs in {(end - start).TotalSeconds} seconds");
}
observe collider prior to start game
then see that there's invisible boundary where it was at the start (I cant walk past it)
despite the gizmos itself showing the collider moving with player
I've been finding conflicting information, does the getter for Renderer.material allocate every time you access it, or just the first time you access it on that renderer?
first access
Okay that's not so bad.
worst thing is, that box is from the parent object
When you say 14s lag spike do you actually see that in profiler?
first tick
UnityEngine.Profiling.Profiler.BeginSample("fs read");
save = await fs.LoadFile($"songData\\{safeName}.dat");
UnityEngine.Profiling.Profiler.EndSample();
file super isnt the major cause, that only added 1~ second to the total task time
its not an issue with it taking 14s, i just dont want it lagging everything else while its doing it
Hmmm... is there any reason you keep the collider enabled after picking the item? Does it happen if you disable it?
enable deep profiling
If you expand the hierarchy do you see several calls to Save/Load file?
stops happening if I disable yeah
But I need it to be colliding
ie I want raycasts to hit it
Are you sure it doesn't collide with your character when you pick it?
No, it stops colliding with my player strangely enough, I suppose its related to how its just staying in its original position
which makes sense if I disable it that the boundary disappears as well, and I can walk through it
636 files, two call per file, but i wrote the FileSuper library myself and its only using about 1s of the total 14
Try putting it on a layer that does not collide with player(after equipping)
I can try
That doesn't answer my question.
but I think i will need to do rigidbody move instead of transform.position setting
Are you moving it with transform?
well thats useful, tho ill have to figure out how to actaully fix it
same happens in build?
Okay, then obviously it wouldn't respect physics properly. It could be why it's actually not updating the physics position.
weird nuance
That means that everything happens in the same frame.
maybe it says somewhere in documentation
(i dont remember all details of documentation)
Which points out that your load and create methods aren't actually async.
The sole reason I'm recommending to avoid the asset store is because I have been in your shoes, and what I've learned is that this "time saving" doesn't exist, using an asset from the store will not save you time, it will only hinder your learning and give you bugs in the future.
Just to be clear, I'm not here making the argument that you should do everything by yourself, I work with Unity by choice, I could have made a game engine but when I started I couldn't do a better job than a group of senior software engineers.
My argument here is against the Unity Asset Store, there's no quality control there, the reviews are made by people that are basically anonymous - regardless of the rating (1-5) you don't know if the person who reviewed is qualified to do so, it could be an amateur who has no idea what he's doing (and of course it could also be a experienced developer).
very one sided argumentation, shaky
If you want to await between files, you should await Task.Yield() after loading a file.
well it seems like the major issue is coming from formatting 636 byte arrays into sprites
Since your API doesn't seem to do that.
which api does that?
this function
Sprite PlsImage(IPicture picture){
byte[] data = picture.Data.Data;
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(data);
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
}
unity api call, synchronous
Yeah, this is just a synchronous method. If you call 600 of them at once, that would obviously take a lot of time.
To make it clear(if that's the misunderstanding), async await in unity is running on the main thread. Similar to how coroutines do. If you expect your whole method to run on a separate thread that's not gonna happen.
even if it did, to use unity api it would bring it to the main thread
Would probably cause errors and crash, but yeah.
my dumbass forget to set FileSuper back to .NetCore, it has a modifier for .Net Framework cos i use it in both
Not sure what that means. I guess you're using a different synchronization context that actually executes the method on a different thread?๐ค
tldr: async .NET framework code is synchronous in .NET core, .NET core async just crashes in .NET framework
I don't know much about using async await outside unity and especially with different dot net versions. All I know is that unity overrides some of the async await stuff to run on the main thread by default.
My 'Wire Gen' Configurable Joints keep getting all twisted. why am i having such a hard time Locking Z?
Here is the code i use to generate the Wire:
https://pastebin.com/JeCMGcH4
i wanted to add sounds to my game, but i think the way i implemented the audio systems might be a bit flawed, but im not really sure why. Basically, i made a static singleton with every sound that i need to reference and then when i need to play a certain sound, like an enemy being hit for example, i get the enemyhit audio clip from the singleton and put it into the enemy's audio source, and then immediately play it;
sound.Play();```
but it doesnt always work correctly, sometimes the sounds just dont play, sometimes they have a huge delay, and sometimes they make my cursor go into the loading cursor for some reason, is there something im doing wrong?
If I create a material instance using renderer.material.whatever, then call Object.Destroy(renderer.material), does the renderer revert back to its shared material, or go magenta or something?
Looks like it will go magenta. blegh.
if the material is destroy then its material is null no reversion no pass go no collecting 200 dollars
hey guys i want to make a simple multiplayer card game. the script would mostly run locally, i just want a few numbers to be shared between the devices (like card number and round number). do you guys know of any tutorials that could explain some basics about this?
Have you read the #archived-networking pinned resources? I would start there.
Yes I've seen them, but I have no idea which ones would be most suitable for my use
If you believe the game to be very simple as you've described, any of them will be completely fine.
I doubt many people have much experience working in different solutions, from what I've seen people will mostly just pick one and run with it.
Fair haha. I guess I'll pick one then :) thanks
Is there some way to extend a class (eg add members) from outside the class definition? Like if I wanted to add a method or something to one of the UnityEngine or System classes
only through transpilers, or as a less hacky but still hacky way, through a lookup table
there are extension methods, but its not the same as a class method
How fast is converting int to uint?
I just want to get use of enum with layers stored in it. So if I want to get the Terrain layer, I will be able just to layers.Terrain (not 1u << some number). But I wonder if it is a little expensive if I will use (uint) conversion quite often?
both int and uint have the same size, the conversion is just changing some bits in memory
its not a little expensive
Almost instant. What a cast does is nothing in memory, only tells "the stuff at this address can be interpreted as something else". And here since int and uint are both value types with the same length in bytes, I wouldn't be surprised if the compiler gets rid of the type check entirely
its so inexpensive that its not a factor at all
dont think thats the case
Understood, thanks. Just wanted to be sure in that idea :)
this can be true if its a positive number, but compiler cant know that
plus its still a value copy
Even for negative numbers, it does not do any checks. You just get a really high number since it underflows
uint Method(int x) => (uint)x;
ldarg.0
ret
Load the value, return it. Can't be faster than this
right, thanks
Is there a way I can put ~0u in enum? To make an "everything" layer there
are you already using the [Flags] attribute?
No. To be honest I haven`t heard of it before you said :)
Each value in an enum gets an integer assigned to it
So I just need to put that flag and than sum all the layers I need for the "Everything" value