#archived-code-general
1 messages ยท Page 400 of 1
you just need to use the local time scale correctly (depending on how you move the rigidbody) . . .
@peak gull first, you need a custom component that stores the local time scale of the GameObject. this is used to scale the speed of the GameObject to give it the slow-motion effect . . .
let me know where you need help at . . .
im not sure where to apply the time scale
im not really sure im applying it properly...
I just learned you can inline define variables in c#...
bool addBrackets = valueObj is IDictionary<string, object> d && d.ContainsKey("type") && d["type"] is Type t && t == Type.Function;
no problem, show us what you have?
changes things, doesn't it?
unfortunently i scrapped it and was going to work on exclusively complete time stop
for sure 
start off with this . . .
but previouisly i made it so on toggle, it would reduce the objects current velocity and gravity scaling by the time, which did work, but on returning to regular speed is where i had trouble, as its velocity would be higher than origin.
it works if there is no gravity but...
i do have a component that stores the local time scale
okay, what does that look like?
its just the issue of applying it, then reverting it back to normal speed
i have a manager that detects if the game should be in the state of "normal" or changed time
all objects that should be affected are added to a list on awake
you need to store its current value, then reset it when the effect is done . . .
when called, each object in the list will have the slowed effect, and the reverse will happen if called to revert to standard time
for example if the speed is 0.5
all objects will see that value and decrease their current velocity and gravity by 50%
and on returning to normal, increase back by doubling it in this case
you can do that two ways:
- store current value, reset back to current value
- modify current value by effect amount by adding or subtracting, then do the opposite . . .
the only problem i have currently is gravity
as gravity constantly changes the velocity
so the doubling of the velocity causes some weird things to happen when gravity does its thing
i tested it without gravity and it works as intended
but with gravity, it would slow down, or speed up on returning to normal time
it'd be easier to affect them using the time scale instead of altering the speed and the gravity . . .
but how do i apply individual time scales
but i would revert the gravity first, then the velocity. have you tried that?
because from what i researched time scale is global and there is no local time scale
i'd need to see your code first . . .
you use the local time scale from the custom component you made . . .
how do i make a local time scale...
the transition from normal time to slowed time works
here's an example of mine. i have my component to track the GameObject's local time scale. the MoveTimeObject component moves the GameObject based on the value of it. currently, it moves at 1/3 the normal speed . . .
the timemanager determines what the strength of the slowdown effect
and player characters are excluded
a quick fix is to store the velocity in a private variable before multiplying by your global time scale, then assigning the velocity to its (previously) stored value upon deactivation . . .
the problem is that if that object collides with an object, its stored velocity will be different
that only applies to complete time stop which i was going to do since i couldnt figure out how to calculate all that physics
when i add gravity it causes this to happen
and i cant find anything on changing timescale on specific objects
as it just applies it globaly
unless i missed a setting somewhere
i have _timeScale; that is local to the GameObject. then i have properties for DeltaTime, FixedDeltaTime, and TimeScale. these properties are used to move the GameObject based on rigidbody movement or manipulating the transform . . .
all i have to do is use those properties when i move the GameObject and it will move according to its local time scale . . .
but how do i apply deltatime to physics
you have to use it correctly based on the type of rigidbody movement . . .
i can program my own gravity and movement, but objects hitting each other is a bit iffy
i think ill just settle with complete time stop
much simpler to program
hold on, i'll just share my example scripts:
So I want to know if what I'm doing is alright. I want to make a Timeline track that allows me to animate gameobjects moving along a spline. For the track binding type, it's a transform, and I have an exposed reference to the Spline container that contains the spline to move along.
Is this... alright? Never messed with exposed reference.
it demonstrates how to use the correct time method based on the type of rigidbody movement . . .
i dont think this will help with what im intending to work for, so i think ill just stick with the simpler idea of complete time stop.
thanks for trying to help me tho
sure, it's just a demo on how to move the objects with an independent time scale. you only have to worry about assigning velocity, calling AddForce, or MovePosition for the GameObject. any script can access the TimeObject class to change the local time scale for that GameObject to give it an effect . . .
i just tested collision using velocity; they still maintain their current speed with their local time scale . . .
So apparently, when you are force playing another animation, the previous one playing sending out all animation events
I don't want that, any workaround known?
Except for making a special bool check on event callback
Theres a way to check the event's state weight if you use AnimationEvent as parameter
I don't get it
From AnimationEvent you can get its .state and there you can get the .weight
how can I use an AnimationEvent as a parameter if it's a callback
Something like```cs
public void MyAnimMethod(AnimationEvent evt)
{
if (evt.animatorClipInfo.weight < 0.5f)
return;
```
AnimationEvent is a class that can contain a string, float, int and/or Object
IIRC you can keep the event in the animation as it is
okay I got the concept
but I don't think that I could get any useful information out of the weight
Theres probably a way to check if its state is the current playing state or not
- animation with an event plays
- I force playing totally different animation through code
- even fires
So the issue is the events fired by the previous/fading out state?
You want to ignore those?
yeah I want to skip the animation and discard all events caused by that
Well thats what i was explaining
oh well
I just realized that I am starting to play the same animation
not the another one
and I still want to discard the event
gonna try the timecheck
im trying to make a script where you have to collect fuel to power the generator. the generator works the first time i collect the fuel but the second time i click on the fuel the bar doesnt apear or the fuel counter doesnt increase
https://hastebin.skyra.pw/kujopabidu.csharp
that's not related to the question but
genOnScript.GenBattery.fillAmount -= 0.0001f;
what you do there?
you should multiply that by Time.deltaTime probably if you want that being not frame dependent
oh ok ty
sounds like you have a few moving parts, so the issue might not even be here
you should debug to narrow down where the issue is
aight ty
Discard everything I ve told, I totally forgot that it was in fact not the event at all, but OnStateExit
A query, if i want to change a property of a component through script for all the gameobjects that are in the scene and have that component what should i do,
for example i have several water bodies in my project at different place and i need change their buoyancy when a certain button is clicked,
do i have to search and store them in a list or array with tag and then loop all through to change it or is there anything better
do all of the objects always have the same buoyancy value?
yeah it has to be bcz i can switch waterbodies at same time
actually i am switching between floating and diving so i hope u got the point
so make the backing field for the property static, that was you can change them all in one statement
backing field ?
you do know properties have backing fiellds, right?
nope sorry
is buoyancy even in a custom script or a component field?
got a question how to change component's field
component field and to be changed thru script
get that component in ur script and u can change any field in it
ok
int myprop { get; set }
this is a property with an automatic backing field
int myint;
int myprop { get { return myint;} set { myint = value; } }
this is a property with a manual backing field
I mean if it was a custom script I would slap a ScripableObject or as you said a static propery field, that sounds nice
but if it's a unity component, well
no idea how to make it so that component use my custom property as it's value
steven can i send a ss of the script
sure
ok, so none of those are properties
ohh i see
they are just fields. so make the buoyancy field static
to be correct, when i am declaring buoyancy class variable that has to be static
like this
yes, if you want the same values to be applied to all objects
I ain't getting it
can a component be static?
kk let me try, Thanks
any variable can be static, that is, after all, how singletons work
that sounds like you can assign one component to multiple gameobjects and I don't comprehand
can you do that?
no, but this is a user class, no
buoyancy effector 2d is a user one?
it didnt work though
and no it is a unity component
well you'll need some way to initially set it
best thing i can think to do is add the Buoyancy component to an empty game object and in your script treat the reference like it was a singleton
but you have to have a buoyancy script on each body of water don't you
i did tried that but as you know buoyancy effector needs rigidbodies
Ah, so you cannot have just one shared Buoyancy class
that's a regular unity component it seems
Yeah but I have no idea what it does or how it works, it's a new one to me\
it's just density that you have to set, right?
just make another component, singleton if you want, that holds the density
then for each body of water that you want to change, have it reference that component/access the singleton to query for changes
just a guess: you might want to query it for changes, and only if it's changed, set the new density? in case there's extra costs with setting the density
so like there are these 3 so i create a new script and then change density in and then call that function to where i change
that's the question if you can do something better than having a list of references to go through each time value changes
Another option would be to use an event which fires when the density is changed
but will it change on all the gameobjects
that's the same thing
if the objects subscribe to the event, yes
wait can they not?
no it's not
how they will as they are a prefab.
should i just attach a script that subscribes to the event
yes
to the prefab
if you're going for events, yes
subscribe on awake unsubscribe in destroy I guess
kk i will try and check then,
just to be confirm again the event will be in the class where i am triggering right ?
where i am switching the mode
don't event thingie internally store a list of event subscribers
so it's really the same
this is a singleton right ?
kinda
kinda, the difference is being on the inside calling out or being on the outside calling in
ok I broke my brain
the difference is which is responsible for the change
with a list, the thing holding the list is responsible
with an event, the thing subscribing is responsible; it's just told that something happened, it has to do the change itself
yes, or at least, the basics of the singleton pattern, it's missing the initialization code
initialization mean on awake right, instance = this;
yes
yup i did it ๐
ok guys i found another solution wanna listen if i am not bothering ๐
as in reality water never changes its buoyancy what effects sinking or floating is the mass of the object so instead of changing buoyance i changed the mass and a little bit gravity on the player so it will act same on all water bodies.
Actually irl, the buoyancy of a body of water is relative to it's level of salinity, but who cares?
I keep forgetting how good extension methods are
I'm doing Ui with vertical layout group and for some reason when I add items the spacing is so huge but I checked the padding and spacing of the items and it is all 0
Ive got some classes that store Vector2, but I need to get them as Vector3 (just without a y value), and it was getting really annoying having to write
new Vector3(myvec.x, 0f, myvec.y); over and over again
Also for some reason the words are placed in the middle even though the child alignment mode that I have chosen is middle left
The trick is to use this
public static Vector3 ConvertToVec3(this Vector2 vec, float yValue = 0f)
{
return new Vector3(vec.x, yValue, vec.y);
}```
It's a place for asking for help or/and help people.
you can then write myvec2.ConvertToVec3() and thats all there is too it
If you want to make a devlog, #1180170818983051344.
I was getting to that
what I'm not sure if is what is this kind of thing called? like the term that describes how that kind of extension works
I know its an extension method, I just mean the overall concept of what they are
like how OOP has encapsulation and polymorphism
They are their own concept.
aah
does C# have any other things like this? I know a number of little tricks that let you write simpler and less obtuse code
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
C# has hundreds of features.
yeah, a lot of the ones Ive found were more or less stumbled across
for instance saw somebody use a lambda like float Diameter => Radius * 2f;
That isn't a lambda. That's a single line statement property.
I always forget the correct names of things ๐
This is a property being defined as an "expression-bodied member"
I've always found the C# documentation to be a bit tough to understand. Like in the expression bodied member page, I understand the way its explaining things but a lot of that is because I know what this is
though I suppose it being tough to understand means its good, because they arent dumbing everything down
There's a lot of terms I tend to forget
I found they never really mattered to me in any projects as long as i knew what i was doing so they just slipped
yeah, i've overwhelmed myself in the past when I tried to do a big "lets learn as many new things as possible", the information never sticks
which is fine, when you work on your own. As soon as you need to communicate with others correct use of terminology is imperative
so you would prefer people to say 'a void thingy' rather than 'method' ?
I find its easy to try and find new features when theres a very clear "this doesnt seem like a good way to write that". Like in the early days I'd look at a wall of if else blocks and that made me question that approach
But expression bodied member is not one I would know off the top of my head
Despite the fact I know how to use one
over time ive picked up a lot of tricks like that, issue is its usually really obvious things that stand out
its all those things I've never noticed that elude me
I'd have never realised you could do this
Vector2 Center => new Vector2(x, y); wouldnt have stood out to me
it was only coming across somebodies code where they wrote new(x, y) that caught my eye
knowing what things are called makes it significantly easier to communicate
oh yeah, 100%
I TA'd a class for college freshmen that used C++. I found it very useful to be able to exactly name every concept I was describing
(i wound up reading a good chunk of the standard)
I tried learning zbrush years ago, and the hardest part was that I had no idea what youd call certain things. Moment something went wrong, or I couldnt make it do something, it makes it hard to look for help when the question turns into "this something isnt doing whatever some action is"
the florpicator
I find chatgpt can be helpful to explain certain concepts or features, especially as the wording of the question can be extremely vague and badly worded, which generally it will be when I only have a vague idea of what I want to know
I dislike using it like that, Google has always been my go to for most things, but past couple of years its search results have started to become useless
I tried looking for information on subdividing geometry and increasing the density of vertices in a mesh, and 5 of the top results were posts asking about poly reduction and doing a low-poly effect
I tend to use - at searches if that happen
not always helps tho
- should be filtering out specific words
"-"
But Zbrush has documentation for the editor. You should be able to search/scroll until you get to the section where you use(d) the thing . . .
needle, haystack :p
oh yeah, ive used google for probably at least 2 decades now. built up a lot of skill on making it provide the best results
the secret is site:reddit.com
I cant be the first one to notice it, but it feels like they've made the search algorithm prioritise providing the most amount of answers to a search, even if it means totally ignoring what you requested (and without it doing the "showing results for" thing)
in the past you could search for pretty niche and strange requests and it would return maybe 8 results. Very good when theres a very specific issue, which there usually is when writing stuff
but if it detects the result count wont be as high, it sometimes seems to go "the user probably meant to use this other word, that gives millions of results, so thats what I'll return"
when I'm looking for information about a video game, the results are dramatically better when I filter to just reddit posts
otherwise you just get a tidal wave of content farms
like when I looked for stuff on increasing polygons for a mesh, maybe it detected there are less results than (the definitley more popular question) of making a model have less polygons, especially for gamedev where people like a lowpoly style
I keep meaning to write searches that do this down, I always forget in the moment
"worlds widest escalator" is one
it insists on swapping "widest" with "longest"
yeah, the number of possible relavent results goes up. And the number of results overall goes down
makes sense that if it figures I searched with one word with poor results, but a synonym for "wide" gives better results, it figures thats what Id mean. And its honestly good for most searches as it probably does that a lot where it interprets my search to have meant something else
have you tried yk now google?
but if it can make such a bold assumption, providing totally wrong results to what I want. Its no wonder why it struggles to help me find answers to some programming questions
Hi, I'm trying to do an OnGround() method for my player but whenever I try to use it on a terrain collider to determine that the player is over it I get a true just at some point but not all the time, this is my function and a video showing the issue (I only move the player if the method returns true)```c#
private bool onGround()
{
return Physics.Raycast(transform.position, Vector3.down, out hit, 1.85F) || rb.linearVelocity.y == 0;
}
how does your hierarchy look like?
I suggest drawing the line to see whats going on. If you're raycasting from the rigidbody itself, the ray should be a little more than half the size.
like this, right? c# void OnDrawGizmos() { Gizmos.DrawRay(new Ray(new Vector3(transform.position.x, transform.position.y, transform.position.z), Vector3.down * hit.distance)); }
Also make sure ground checks are in Update, not FixedUpdate
wdym? I'm applying the movement on fixed update, that's why I'm checking there
void FixedUpdate()
{
if (onGround())
{
inputSpeed = (transform.forward * input.y * speed) + (transform.right * input.x * speed);
rb.linearVelocity = new Vector3(inputSpeed.x, rb.linearVelocity.y, inputSpeed.z);
}
}```
Ah no, im tripping. You're ok
yeah this looks good
there is no line
one sec
btw, this worked fine when I tested it on a plane
and when the terrain is not flat it also works fine
public float lineLength = 5.0f;
public Color lineColor = Color.red;
void OnDrawGizmos()
{
Gizmos.color = lineColor;
Vector3 startPosition = transform.position;
Vector3 endPosition = startPosition + Vector3.down * lineLength;
Gizmos.DrawLine(startPosition, endPosition);
}
// I draw mine like this
I tried using Gizmos.DrawLine with transform.position as origin and hit.point as end and now I have a line from player to 0 0 0
okay, looks like I found a fix to this
For GroundCheck i also recommend making a child on the base of the player
i think its up to preference of the designer, but sphere checks work better for me
I moved my player to layer 2 (Ignore Raycast) and moved the origin of the raycast to transform.position + new Vector3(0,1.75F,0) because 1.75 is the height of my collider
do anyone know how to fix this?
I'm not sure why that happens ๐ญ
that picture doesn't help us see what is happening (clearly). also, you may have better help in #๐ฒโui-ux
#๐ฒโui-ux but also could you provide screenshots of the settings on your vertical layout component?
wait for some reason jn when I checked it was fine but when I changed scene and come back the panel became a cross instead
This is a #๐ฒโui-ux question not a code question
okiee
and the red X means your object has a negative height or width
I'll try ask there
should jumpForce be in Newtons for rigidBody.AddForce(0,jumpForce,0)?
When using the default force mode, AddForce forces are expressed in newtons, yes.
Most likely for a Jump you want Impulse mode or VelocityChange mode.
oh, got it
I'll change it
now I understand why I needed to set it to 10000 the jump force with default mode XD
yes, because an instantaneous force isn't really meaningful
yeah
how should I clamp the euler angles of a transform? I tried using Mathf.Clamp but it's doing weird things
how exactly are you trying to limit the rotation?
my code is this```c#
private void MoveCamera()
{
switch (type)
{
case MovementType.FixedToBody:
transform.Rotate(0,input.x * sensibility.x, 0);
cameraTransform.Rotate(new Vector3(- input.y * sensibility.y, 0, 0));
break;
case MovementType.Free:
cameraTransform.Rotate(- input.y * sensibility.y, input.x * sensibility.x, 0);
break;
}
cameraTransform.rotation = Quaternion.Euler(Mathf.Clamp(cameraTransform.rotation.eulerAngles.x, -90, 90), cameraTransform.rotation.eulerAngles.y, cameraTransform.rotation.eulerAngles.z);
}
What kind of object is this and how are you rotating it? Is this mouse input?
The best practivce is to drive this with your own float variable rather than trying to read euler angles back from the Transform.
Reading euler angles back and doing logic based on them is always a bad idea
You cannot isolate individual euler angles and hope for a sensible result.
the input is a Vector2 variable read from Input system
yep, - store float variables and clamp those
instead of reading the current back from the Transform
agreed
so store the angle and set the stored values directly?
clamp the float instead
yeah, that was part of "store the angle"
I mean store the clamped angle and then set it to the quaternion without reading the current angles
the input is a Vector2 variable read from Input system << this needs to be clamped
I'm trying to figure out how to cache Randomhide to make sure it cannot pick its current index again (line 122 to 133), can anyone help me out? Yes I know the code is horrid, I will try to optimize it later if I can.
https://paste.ofcode.org/FaavNFQGVQ7G6yGKeVmkjc
Thanks, now the camera is working perfectly
direct solution: check if it's the same, if it is reroll, repeat
without loops: randomize to 1 less than normal, if it's >= the current value, add 1
also consider shuffling instead of randomly choosing, dependng on what you're using it for
I'm just trying to choose a random hiding position based off a dot product from some normals I calculated, so this should be fine
I am going to create an inventory system for my game. I tought that system for it:
Every slot will have an ID.
Every item will have an ID.
The slot will check if there is any item (ID) placed into slot.
However, I am stuck because I cannot figure out how to assign an ID to each slot, so that the player can select the slot by pressing a number on the keyboard or clicking it with the cursor. Can you help me with my issue? Also, please suggest a better system if you have one
what have you tried already?
you probably don't need anything fancy for the slots ids, just a unique incrementing number
1- no
2- i havent made an inventory system before i just tought how can engine ever dedect exsistence of slots without id
You can always use Guid.NewGuid() to create a unique ID. But a number would mostly be better in this case.
i did draw this for hotbar , should i import like that or add squares individual
It might be a better idea to work with single cell. If you ever want to increase the size it will be easier.
i thinking 16 for rest of inventory and 4 for hotbar
20 slots in total
hey! I made an animationw here my characters arms raise above their heads in my first person game. but as you can see their hands kind of get clipped off weirdly. is the only fix for this moving the camera to a better spot or can I somehow allow the full arms to be rendered regardless
The meshes are getting too close to the camera.
This is determined by the near clip distance on the camera.
You can reduce this distance, but if you don't reduce the far clip as well, you'll lose some depth precision
so z-fighting will happen more frequently with nearly-overlapping surfaces
I do find the default values (0.3 and 1000) to be pretty conservative
(note that this is not a code problem; if you have further questions, ask them in #๐ปโunity-talk )
hello! Happy christmas everybody. I've got a quick question, does PrefabUtility work when running the compiled build?
No. Nothing in UnityEditor exists in the built game.
Prefabs barely exist in the built game at all!
(as as concept, at least)
Yeah, they're just instances at that point
instances that live in the Negative Zone, but instances nonetheless
Kinda annoying lesson to be learnt where creating a large prefab base to have loads of nested prefabs on top of is a bad idea
because the base is just baked into each of them
i mean, that's a given
I guess you wind up with a little more serialized data than you'd expect?
Yup
especially if you have components that store giant binary blobs inside themselves
I made a card game once with lots of variants of animated 2D sprites and the variants bulked out the game something insane
had to make a system to manually spawn the base object to avoid having massive things which are just variants
how did you wind up with sprite data inside of the prefab assets?
complex animated sprites can serialize a lot of settings and hierarchy which ends up adding up
and UGUI was involved too
and it's just as bad
to ask a question about a code issue that I have, do I post it in #๐ปโcode-beginner and follow the Dos and Don'ts in #854851968446365696 ?
Yes..?
sorry, I wasn't sure, there are a lot of rules for this server and it seems very strict so I don't want to mess things up
It's ideal if you follow the guidelines, but you'll see that many people here don't do that. If you follow at least some of them and use common sense when asking your question, that's already going to be good enough.
alright thanks!
Besides, if there's a blatant issue, the community members would likely guide you in the right way to address it.
alright, sounds better than other servers I've been in, last question, I should make a thread for my issue right? I'm only asking because I see some coding questions not as threads in the channel
If you think it's gonna take a long time/discussion to solve it, then yes. If it could be answered in a few messages, it's fine outside of a thread.
alright, thank you again
I should be able to just import whatever nuget packages to my unity project through my IDE right?
No. The ide project/solution is generated by the unity tooling and has no effect on the unity project itself. It's mostly just for ide compatibility.
You import packages into unity via the unity package manager.
hmmmm ok, my issue with Rider forgetting the only package I have installed is unrelated then.
So I am filling out a nativearray in editor, and taking it with me into playmode, but I think unity thinks this is a memory leak, so it yells this at me. is there a way to stop it from yelling at me? I FULLY intend to take the nativearray created in editor and its contents over into playmode
Native arrays usually have a limited lifetime depending on how you initialized it. And obviously, they would need to be disposed of before domain reload(something that would happen on entering play mode by default), since the reference to it would be lost and cause a memory leak.
To put it simply, you can't keep the same native array alive between editor and play mode.
So
Why does the data stay?
Why can I still access it in play mode without recreating it?
Can't really answer that without seeing the relevant code and knowing how you're confirming that.
hi guys how would you manage this skill tree
in have 5 different counter. each count how much ive spent in a category. Now each skill to be unlocked needs to meet the requirement of "spend 10 in category1, 20 in category2" and so on and this check should be done every time i upgrade a skill in a category (upgrading a skill means spending in a category).
Should i store all the unlocked skills in a list and iterate through them? i have atleast 50 skills so it seems wacky to me to iterate through 50+ elements every time i upgrade. I was thinking about firing an event from each skill so that they check the requirement by itself but then i need a reference to the skillmanager to unlock the skill
maybe a coroutine that checks that?
Modern CPUs can easily do millions of instructions per second, checking 50 skills is hardly anything, especially when the check only happens when player upgrades the skill, it wouldn't even be noticeable to the player that clicking the upgrade button is a few nanoseconds slower.
yeah i know this i was just wondering if there is a better way anyway ahah!
also the target is mobile (which shouldnt make any difference)
i dont know what the name for it is exactly but when you "drag a gameobject" into this little box to refrence it (like hinge here)
what is actually going on code wise for this to happen?
is there some other script somewhere keeping track of what object refrences what?
A script? No. The scene or prefab stores that data
The scene or the prefab contains all the information about the objects inside it.
when you "drag a gameobject" into this little box to refrence it (like hinge here)
what is actually going on
The reference is being stored in the scene or prefab
just like any other values
same thing for if you checked that "Closed" checkbox
it gets stored in the scene or prefab this object is contained in
You could implement some smartass way to sort all the skills by the total required points and use a binary search to get to the corresponding skills, then find the one that satisfies each category requirement. But honestly, that would be an overkill.
If you had millions of skills, that might've been worth it, but I probably wouldn't do it even with 1000 or 10000.
You'd think that there must an easier way to solve it, because of how easy it is to solve it in our brains. But in reality your brain is probably doing some complex incomprehensible logic before you get the results. You only see the true difficulty of a problem when you try to implement an algorithm to solve it.
thats totally true
sometime im thinking how can i make something better and when you do it you think of it again
where do i learn c#
check the pinned messages in #๐ปโcode-beginner
good luck on your journey!
ty i might just give up half way
nooooo!! lol
c# is fairly an easy language. just gotta understand the oop concepts
how do I strip "STEREO_INSTANCING_ON" from shader? thanks in advance
please don't crosspost
what?
please don't post the same question in multiple channels
and this doesn't sound like a code question, perhaps try #๐โanimation
if i get it right hands got behind the camera so this view got exist
solution : lift arms less or change the position of arms/camera
How to get object facing direction in 2D? My game object isn't rotated at all: in the editor euler rotations show 0, 0, 0 rotations, yet when I'm calling transform.forward.x, it returns 0?
I want to set and get the rotations in 2D with vectors, but if I do transform.forward = Vector3.Left or transform.forward = Vector2.Right, the sprite simply disappears.
I got this error down below while working with navmesh agent
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination (UnityEngine.Vector3)
I already baked the navmesh surface around the map
transform.forward is the z direction
if it's not rotated it'll be (0, 0, 1)
you probably want transform.right, and if you want to flip, you could also use localScale.x *= -1
I first flipped character with scale, then switched to using euler angles but I think it's better to work with vector, because I often want to use if character is facing left or right
I used a separate variable for that, but transform.right and working with the vector should allow to get rid of that
And use nice math functions like Math.Sign(transform.right.x)
i think it's better to work with vector
this.. doesn't really mean anything
scale and euler angles are also vectors
a vector is just a list of numbers
I mean the geometry direction vector
...so, transform.right?
Yep
im not sure i'd call that a geometry direction
just the direction of the game object
i mean it still kinda is an euler angle
and underlying it all, rotation is a quaternion
Sure, I just think math and code is much simpler while working with vectors
the raycast works and destroys the sticks when i hit them but it just doesnt increase by 0.1 when i hit it https://hastebin.skyra.pw/vuladuseva.pgsql
What doesn't increase?
the Vector3 newscale
Where does that live?
Which object did you reference in the inspector?
player
From the scene? Or from somewhere else?
scene
in firstpersoncontreoller
ok and would you like to show that code? What makes you think it's not increasing?
Show the code I mean
No I already saw this. I want to see the code for FireFadeAwaySticks
well for one in the other script you're multiplying the increase amount by Time.deltaTime;
which means it is going to increase by a very small amount
ohhh ok
and then in this script you're decr3easing by FireDecreaseNumber EVERY FRAME
mneaning it will decrease very quickly
you put deltaTime in the wrong place
it should be used in FireFadeAwaySticks, not in the other script.
ok so time.deltatimeshoud be used infirefadeawaysticks no the other one?
cuz when i add Time.deltaTime in firefadeawaysticks it just decreases too fast
add it how
that makes no sense
if anything it will make it decrease slower
Time.deltaTime controls rates, it's seconds per frame, you use it to control how fast something happens
you don't multiply it onto a the scale directly, that would just make it tiny
yeah no, that's not what you want
you'd have to multiply it on a rate of change of scale
transform.localScale -= Vector3.one * ireDecr3easeNumber * Time.deletaTime; this is what you want @onyx cypress
oh ok thank you bro
waitmy bad for asking you again what is wrong with this again
You tell me. What's wrong with it?
the thing stilld oesnt increase
This code has nothing to do with increasing anything
First step is to use Debug.Log and make sure that line of code is actually running
and you can print the value out too
to ensure it is increasing
you can print the value before and after the line that increases it, to see what's happening
so when i debug it shows maybe it st increasing very little
it is increasing by exactly the amount you told it to
But why are you saying "maybe"
if you logged it, you would know for sure.
yea it is
but its not that small of a numebr it wouldve made a different to the vector by increasing it
Anyone that understands about 2D and tilemaps can give me a hand?
not if you don't say what you need help with https://dontasktoask.com
I cant spawn the guards on the right place The guards on the top spawn perfectly but not the ones on the bottom. My code is in the .txt message. I really dont know why it's not detecting the tile map sideways but detects upwards
i am sure
what and where exactly is the issue?
I do believe its somewhere on the "FindNearestMiddleofRoad" function, I just put the rest so you guys can understand the rest. But where exactly I dont know. Cause I asked chagpt to do this, I dont really know the syntax to do stuff on tilemaps
there's nothing special with tilemaps in regards to syntax
I've been like 5hrs trying to figure out what is wrong there
What I wanted was for the guards on the bottom to go to the right side (on this case)
And for some reason it's not detecting the tile map sideways
ok but I dont know much about unity yet and like I dont know this "roadTilemap.WorldToCell(startPosition);" or "Mathf.CeilToInt(searchRadius);" or "roadTilemap.CellToWorld"
what are you logging here?
show the value of the thing you are increasing before and after
oh ok
I believe it's pathfinding. Because they spawn ok, just not on the right spot
just not in the right spot
....so, they aren't spawning correctly, then?
yes, but because of the pathfinding, because it does not detect the tilemap
....do you know what pathfinding means
pathfinding doesn't really have an effect while spawning
maybe I do not
like thjis ?
I have no idea because you're not showing the code
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
looks like it's workjing fine to me
no?
I don't see a problem here.
more or less
oh ok but still doesnt work for some reason must be a issue somewhere else idek
"doesn't work" is extremely vague, but yes, the problem must be elsewhere
cuz the thing is only two scripts are connected to the fireplace firefadway the this one
and u said the other one is fine and same with this one
it says the x, y and z transforms is increasing by 0.10 in debug.log but isnt actuallt increasing in the fieplaces transform component
Well which object is that script actually attached to?
because that's the one it will scale
its attached ot the player
Then why would the fireplace scale?
wait do tou mean the firefadeaway? if so it in the logs script other one is in player to collect sticks
I mean whichever script has transform.localScale = ...
that's going to change the scale of the object that script is attached to
try debugging each step
is the position right? is the cell right? did you pass in the right tilemap? etc
Like the tilemap of the road its all the same, and its just the road, the rest like decoration and stuff are on another tilemap, the tilemap of the road as the tag "path". And I'm going to debug everything again after I eat lunch and I'll let u know
were do I go to find help with animation masks issue?
thats the one thats atytached ot the hlogs
"the logs" is not a GameObject
wait when you mean gameolbject do you mean wheere the script is attached to in the scene?
when you told me to add the localoscale code earlier this appeared what does this do?
yes what else
I never told you to add anything like that
that's your variable
Oh ok i might need to rewrite the whole sticks thing its getting confusing
wait when i said the logs i emant like the actualg gameobject logs in the scene
did u think i meant the logs int he console'=?
Yes I thought that. I have no idea what your game is about
IDK what "logs" are in your game
then go use Unreal, good luck with that
Sticks
Yeah blueprint no thanks
love the way people seem to think that stitching a few 3rd party blueprints together is actually game dev
i mean
Been a few months of redoing prototpe code and extending some functionality / updating personal packages and now I realise the code works like a labyrynth of delegates
Time to shoot it in the face and redo the plumbing, tear out 90% of delegates and just keep the necessary ones cause this has gotten hard to follow
Honestly completely redoing entire projects if youโve been learning how to do what you want but it ended up messy is a fine idea
Itโs a lot easier to just write new stuff than refactor the entirety of your code base tbh
Just have the old solution open on another vs window and copy paste anything you can
Yeah I share that sentiment but even in this state the code base is several times cleaner than what I have to deal with at work. I just have too many decouplers for components that clearly depend on each other to work, so welding them back together and redoing the flow should not be too hard and will read much better ๐ค
Is calling a method in fixed update the same as calling a coroutine that includes yield return new WaitForFixedUpdate();
Is there any slight differences?
No
WaitForFixedUpdate resumes after the physics simulation. FixedUpdate is before it.
You can see the whole ordering of things here:
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
so is my only option then to make it a standard array? to keep it between domain reloads
Why not write it to an asset or file?
cuz its up to gigabytes of data
What is the use case?
and it can be many many many many files
you still haven't shown us what you actually did
But why does it need to exist exactly at this threshold of edit mode -> Play mode? Won't you need it in the build too?
yes but it can take several minutes to fill it out
so I would rather do it just once in editor, then be able to go into play multiple times
I am trying to create a coroutine that causes the enemy to detect any thing tagged with obstacle around it, and if there is an obstacle around the enemy, it causes the enemy to jump. However, it is not working properly:
private IEnumerator CheckForObstacles()
{
while (true)
{
// Only check for obstacles if the enemy is grounded
if (isGrounded)
{
// Perform a CheckSphere to detect obstacles within the specified radius
Collider[] hitColliders = Physics.OverlapSphere(transform.position, obstacleCheckRadius);
foreach (Collider hitCollider in hitColliders)
{
if (hitCollider.CompareTag("Obstacle"))
{
isJumping = true;
// Apply an upward force to make the enemy jump
rbody.AddForce(Vector3.up * jumpForce, ForceMode.Force);
Debug.Log("NoAirMoveObstacleSimpleSlopeMeleeEnemyController: jumpForce has been applied");
break; // Exit the loop after detecting the first obstacle
}
}
}
// Check if the enemy is in mid-air and set isJumping to false
if (isJumping && rbody.velocity.y <= 0) // Enemy is falling or has reached the peak of the jump
{
isJumping = false;
}
// Wait for the next fixed physics update
yield return new WaitForFixedUpdate();
// Wait for the next frame (LateUpdate)
//yield return null;
}
}
not quite sure what to show tbh
I just create the nativearray in editor with persistant allocator and fill it out
it is not working properly
- What are you expecting it to do?
- What is it doing instead?
When there is an obstacle, I want it to jump. Instead, the enemy doesn't jump when there is an obstacle near it.
Ok and what debugging steps have you taken?
- Have you ensured your coroutine is actually running?
- Have you ensured isGrounded is true so the overlapSphere actually runs?
- Have you checked which if any objects the OverlapSphere call is hitting?
WAIT I DONT ACTUALLY NEED THIS ARRAY IN PLAY!
probably why I thought it was working...
wait but I do
Heck I am probablyt able to dispose it but still use the allocated pointer... to read into technically uninitalized data that just happens to still contain the data for the array
โจ
That sounds like begging for trouble tbh
I agree
I am fixing that now
do I need to deallocate pointers themselves?
I dont think so but just to be safe
But the entire reason I went to native was because I got so sick and tired of half my RAM use being reserved memory, since i do most of the ram heavy work in editor, it has some difficulty freeing it
The couroutine is running
isGrounded is true, but the enemy just hovers instead of jumping
The overlap sphere hits all the objects that is within it, but it only does anything if the collider has a tag of obstacle
were you actually having any kind of problem, or were you just looking in the task manager and seeing a big number?
okay, but were you having any kind of problem?
no cuz I have 64 gigs of ram, but I do NOT trust windows/unity to free that reserved ram if needed in editor
i wouldn't re-architect a bunch of my code to solve a problem that doesn't currently exist
well since this is meant to be used by others mostly... I cant really ignore possible problems
since I have 64 gigs of ram, its unlikely ill normally run into RAM problems, but 64 gigs of ram is an uncommon case
I would sincerely hope you have a great deal more than 64gigs available because 64gigs ain't a great deal for a multi tasking OS
what?
perhaps if you're trying to run five different CAD programs simultaneously
what I said, never heard of virtual memory?
I don't see how that's relevant to what you claimed
obviously, no modern operating system is operating in real mode
You're talking about programs, I'm talking about the data (and thus the ram) they require
I have 32gb RAM, and virtual memory (the page file) on my device disabled. It is plenty for developing in unity or just multitasking in general. it's a bit ridiculous to insist that 64gb is not enough and that virtual memory is a must in this case
(well, you're always using virtual memory, since you are not operating in real mode -- you are simply not having to page anything out to disk)
I still have no clue where this assertion about 64 of god's-own gigabytes not being sufficient is coming from
Depends what you are doing, open a few Unity projects, blender models, gimp images + browser pages + Discord (not to mention the OS itself)
The guy said ram then you said I hope you have more than 64g total
Heโs not running windows off a floppy disk is he
not everyone uses chromium browsers
also cutting back vs for vs code saves you like 4 gigs
I'm going strong on 16 at home and our work mini M1s I believe come with 32 and they're definitely not struggling on that with multiple 3d and asset heavy projects open. That's a wild claim ๐
weird, for some reason visual studio has stopped showing errors
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
I dont think thats the issue, its not that its not showing up only for unity stuff
This should be showing up as an error
what error are you expecting
Center and Size havent been defined
you sure they aren't just defined on IShape?
they arent
this also should have an error because I havent implemented anything from IShape
try hovering center/size/ishape and see where it brings you
Assets\Source\Geometry\Shapes\PolygonShape.cs(5,32): error CS0535: 'PolygonShape' does not implement interface member 'IShape.GetBoundingBox()' unity registers the error just fine
and btw, unity vs non-unity has nothing to do with this
Its just plain text
ok so it's lost its configuring
does restarting work?
does restarting the language server work? (if that's a thing you can do on vs)
restarting VS seemed to fix it
box of black magic moment
im not keen on "turn it off and on again" being the fix
i mean if it happens again then maybe there's a deeper issue
but if it's a one-off then.. i mean, stuff can be finicky sometimes
reloading the solution/project would have fixed that as well. it's just that restarting visual studio obviously does that too
I wonder if theres already a basic geometry library, would save me the hassle of trying to implement it myself
there most likely is
https://github.com/isadorasophia/murder/tree/main/src/Murder/Core/Geometry I've just been taking stuff out of this
a lot of people are saying this
yeah if you could fucking stop replying to my messages with this useless phrase, that would be nice
lot of people are saying this
aaand VS isnt giving errors anymore
make sure visual studio is up to date. it seems like you're experiencing an issue that was fixed in a recent update
just checked, it says its up to date
what the hell, the errors just appeared without me doing anything
lsp loaded
How many times do you have to be told to stop doing this?
How would I go about being able to place cheese?
Essentially I have a plate with a burger patty on it and a drawer where the cheese sheets are in. I have gotten to the point, that the player can open the drawer and take cheese from it, but how can I allow the player to place it on the burger patty in a way that is "snapping" to it and becomes a part of the burger patty?
raycasts
what after that?
I can detect the raycast collision but what would I do with it?
I want to make one burger object out of the bun gameobject and the cheese gameobject when I decide to interact
make a component on the bun / collider, when you raycast onto it you press your button and it will just parent the cheese object to bun object , up to you if you use the center of bun or specified offset
that is a thing? Parenting things to an object via script? That sounds useful
ofcourse
anything you can do normally in unity edit mode, can usually be done in runtime including parenting objects
you dont have to create a whole new gameobject
so I found this... interesting asset in my folder... is there a way to check a mesh to see if it has no triangles, without calling mesh.triangles.length?(since thats very expensive for a simple validity check...)
hmm that is great news.
So I would just specify the two objects (base object and holding object), make the holding object a child object of the base and then specify the offset? Sounds simple, what could go wrong ๐
great thanks.
I swear the people on this server are all just good people. Thank you all
I prefer can also work because of this This method is the same as the parent property except that it also lets the Transform keep its local orientation rather than its global orientation. This means for example, if the GameObject was previously next to its parent, setting worldPositionStays to false will move the GameObject to be positioned next to its new parent in the same way.https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.SetParent.html but yeah .transform can also work
This method is the same as the parent property except that it also lets the Transform keep its local orientation rather than its global orientation. This means for example, if the GameObject was previously next to its parent, setting worldPositionStays to false will move the GameObject to be positioned next to its new parent in the same way.
Im terrible
Trigger collider on burger and cheese
Drop cheese over burger
OnTriggerEnter parent cheese to burger
listen to Creep by Radiohead
Hello guys, I started out recently,
I am making a node based game and I am doing the movement with vector3.lerp.
Could somebody please help me with implementing a view bobbing effect?
It would greatly enhance the experience.
I would also like to ask if there is any other way to move between two waypoints other than lerp.
I would imagine there should be lots of tutorials for a view bobbing effect, what have you tried searching up? In terms of movement, there is also .MoveTowards or using physics from a rigidbody, you can also directly set the position, all depending on the kind of movement that you need, and if the movement should care about physical objects like walls, hills, etc - in most approaches, your essentially moving based on a percent value between 0 and 1, where 0.5f is half way or 50% between A and B, how fast that percentage moves from 0 to 1 is up to you, it could be through deltaTime, it could be through an AnimationCurve or some other method, depending on the affect and drawbacks lerp may be having for you atm
I searched up multiple tutorials, however every one of them was for a rigidbody. I wanted to make a node-based system where your movement is very limited.
But my camera only bobed when I wasn't moving between waypoints.
This is how my movement works:
I am initialy in a center position, here I can press a, w, s or d, pretty generic stuff.
Then if I press a I turn 90 degrees to the left then start moving to a door and then if I press s at there I turn 180 degrees and start moving back to the center position.
Basically while the character was rotating I was bobbing and when the lerping occured nothing was happening even tho I didn't turn off the bobbing myself.
Oh yeah and I also tried debugging.
I changed the logic so that I bob my head when I'm not moving and worked perfectly. The camera was bobbing fine. So I'm really close to figuring out what the peoblem is, but I'm unsure as of now.
Hmm, maybe you can share your code and if not myself, im sure someone might be able to provide some help
Probably transform plates local coordinates to global, then set the cheeseโs cords to that when input is detected, with offsets to center it
Alright here is the code piece that does the waypoint to waypoint movement:
System.Collections.IEnumerator MoveToWaypoint(Waypoint newWaypoint)
{
Vector3 startPosition = transform.position;
Vector3 targetPosition = newWaypoint.transform.position;
float elapsedTime = 0f;
while (elapsedTime < 1f)
{
transform.position = Vector3.Lerp(startPosition, targetPosition, elapsedTime);
elapsedTime += Time.deltaTime * moveSpeed;
yield return null;
}
transform.position = targetPosition; // Biztosan pontos pozรญciรณ
currentWaypoint = newWaypoint; // Frissรญtjรผk az aktuรกlis waypoint-ot
}
So why would you expect this
transform.position = Vector3.Lerp(startPosition, targetPosition, elapsedTime);
to do any bobbing?
Oh I'm sorry, this is not for the bobbing.
This is just the moving I think it would be too big to put every part of my script here.
It's actually quite large.
Unfortunately I cannot even copy the part here that I want, because I'm on my phone and I cannot acces my computer anymore for today.
You are supposed to paste your !code into a site, like hastebin, and post the link here . . .
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hello, is it a known bug that there is no stack trace for profilers connected to a build or am I being a bit silly (some option I need to enable)? I am getting an error only but without a stack trace, yet when I look in the log file I can see the stack trace.
unity 6 recommended LTS
hey guys I dont know if im dum or something but the trail renderer is not setting the emiiting to true, here is where I set it:
Can you freeze a gameobject transform ?
in have a player that flips and i want the child to not without making it an idividual gameobject.
You can't parent an object to another object without being affected by the parent's transform.
that's the entire point of parenting
You can use the Constraint components to make one object follow another
I want just the local scale to freeze.
i totally can but you know
if this is 2D, you can just flip the sprite renderer instead of the entire object's transform
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SpriteRenderer-flipX.html
but then that wouldn't affect the positions of other children, of course
thank you
then i ll just get the object to follow the player trough code
Do you guys prefer to use regular C# events (Delegates/Actions) or Unity Events?
I'm kinda confused on them
Is it just preference?
Unity events can be serialized and subscribed in the inspector.
But yes, it's a preference thing. I usually use the plain C# events.
There's no reason to use a Unity event unless you want to serialize it
Unity events are 10-100x slower than C# ones. If you donโt know why you would need the Unity Eventโs features (or what they are), use c# events. Using unity events in the editor to hook up systems is a nightmare to maintain but very helpful in prototyping.
I use Unity events if I explicitly need to hook them up in the inspector
I only really do that when I have something really generic that doesn't have more specific code written for it yet
So, I should only use Unity Events if necessary
Otherwise, C# events
Got it, tks everyone
Sorry to ask again but is there an actual use for Delegates over Actions?
that's a bit of an apples-and-oranges question
or maybe a squares-and-rectangles?
System.Action is a pre-defined delegate type
From what I've seen, Actions just appear to be a simpler version of Delegates
Ooh
So they're just a bundle
You often don't need to define your own delegate types
since you can just use the built-in generic ones
System.Func<int, int, int> takes two ints and returns an int
One big reason to define your own is that you can include parameter names
This can make your code easier to understand
I see
But if I can understand the built-in generic ones, there's no need to create my own Delegate types
You can declare an action/func with tuple argument that has named fields (via tuple syntax).
true (although that's not exactly like having named parameters)
unless that expands into a genuine multi-parameter delegate type?
itโs very similar to what event args would be
Ah, true
since that demands a two-argument function
I've also definitely used "func that takes a tuple" more than a few times
itโs just a quirk, itโs not really great in practice
in cases where you need an args struct, you typically have a better time declaring the struct
When I use the debugger in visual studio code, the window with all the variables being tracked is located in this odd position, and I can't add or remove any of the variables. How do I fix this?
I'm making a color switch type game, and this is my circle manager code (circle is the thing with 4 colors that the user has to get through):
using UnityEngine;
public class CircleManager : MonoBehaviour
{
public float rotations = 100f;
public float despawnAfterY = 20f;
private void Update()
{
transform.Rotate(0, 0, rotations * Time.deltaTime);
GameObject player = GameObject.FindWithTag("Player");
if (player.transform.position.y > transform.position.y)
{
Destroy(gameObject);
}
}
}
the object rotates, however if the player y position is more than the objects, the object doesn't get destroyed, any reason why?
(despawn after y is ignored for testing)
Figure out what player actually is
Perhaps you have multiple Player-tagged objects
Consider logging it:
Debug.Log(player, player);
The second argument is the context for the log statement
it'll highlight the player object when you click on the log entry
Looks like the autos window. You should be able to drag it around. If you can't, maybe disable it in the debug - windows menu.
i fixed it, thanks though
Do people generally use the UI Toolkit editor and attach callbacks (ie for buttons) to elements with specific IDs or do they construct UI Toolkit UIs programmatically?
I'm new to this and I just did a simple AI navigation with the nav mesh surface
However the zombie seems to get stuck randomly even though the surface is flat?
Like it just get stuck there for 8 seconds before able to move again
FindWithTag is slow and very expensive to have in Update since it will be called every frame. typically, you use this in a method called only once and store it in a class variable . . .
Hi currently in my project i have plenty of gameobject all sharing the same material with the same big texture. whats the difference is that each mesh has its own UV located in different part of the texture. this should help to reduce the draw calls. But now im figuring out that i want some difference between the material, let it be some object must emit light, other must have a different shader. whats the best approach? i currently have two shaders. one is an unlit toon shader with some "windy" effect, another is a just the unlit toon shader one
Probably just create several materials and configure them the way you like.
but currently im 100+ batches in the stat page, im targeting mobile so i should keep that low. I dont know what to do to optimize more
Are you actually going under the target frame rate budget on your target platform?
Are you just optimizing for the sake of optimizing?
actually it runs quite smoothly. Doesnt the increase draw calls reduce performance?
might be a yes
It might. The question is whether it reduces it below your budget or not.
Don't do that. It's a waste of time and might cause more issues.
im using a render texture with a low res and i can keep a 60 fps
so yeah you re right, just wasting time instead of implementing more things
I'm trying to convert a class to Json with JsonUtility but its not working. I know instances of the class exist but the string is empty. Any ideas why or any workarounds are appreciated.
*ButtonDisplayable is an interface, so it shouldn't affect whether SimulationRecord can be serialized
[System.Serializable]
public class SimulationRecord : ButtonDisplayable
{
public int day;
public int id;
[SerializeField] private int value;
public PlayerData playerData;
public SimulationRecord() {}
public SimulationRecord(BattleData battle, PlayerData player, int id, int day)
{
value = battle.value;
playerData = player;
this.id = id;
this.day = day;
}
*There are some functions here, although I don't think that affects serialization..?
}```
```[Serializable]
public class PlayerData
{
public WeaponItem weapon;
public BulletItem bullet;
public UtilityItem utility;
public PlayerData(WeaponItem weapon, BulletItem bullet, UtilityItem utility)
{
this.utility = utility;
this.weapon = weapon;
this.bullet = bullet;
}
public int getValue()
{
return weapon.price + bullet.price + utility.price;
}
}```
How are you serializing it and confirming the output string?
Iโm writing to a file, but I also print the string. Itโs actually a list of SimulationRecord but the output is still empty
You can't serialize a list as the root of a JsonUtility call
You should create a serializable wrapper for the list
Itโs a part of another class; SaveData right now. SaveData is an aggregate of several classes that are [serializable], some of them in lists. Everything else is serializing properly except for this class which results in empty list. Sorry for not being clear in my last message
Everything looks fine, so can't say what the issue is without more code
We need to see the relevant code and logs.
How do I upgrade my render pass/feature to use the render graph features in Unity 6? I tried to look at this documentation, but it seems to not have been updated and just renamed for some reason. You can see it says code with old/code with new pipelines, yet the code with new pipeline uses depreciated methods that are no longe implemented without compatability mode (such as Execute or OnCameraSetup). So how do I do it??
https://docs.unity3d.com/6000.0/Documentation/Manual/urp/upgrade-guide-unity-6.html
I have a few things that are saying they're obsolete, but there seems to be no information on what to use instead (thanks unity).
If anyone has any information, I'd really appreciate that. Here are the things that are obsolete in my script:
- renderer.cameraColorTargetHandle
- public override void OnCameraSetup (ScriptableRenderPass)
- public override void Execute (ScriptableRenderPass)
I keep getting error while using the pool
InvalidOperationException: Trying to release an object that has already been released to the pool.
For some reason when I try to release the object it says that it have already been released to the pool?
looking into this more, it looks like almost all the documentation is just... wrong now. https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@16.0/manual/renderer-features/write-a-scriptable-render-pass.html
Are these methods incorrectly marked obsolete?
Then it already has been. Or it was never unpooled properly.
It bugged when I do the ontrigger then explode and release back to the pool
for some reason the triggered function got called twice
Debug what it collides with. Probably collides with several objects.
I've got this Grid, that uses a Rectangle (from a Spline) to get the dimensions.
public class Grid
{
public int GridWidth;
public int GridHeight;
//Grid will be used for a tilemap
public Grid(Rectangle rectangle)
{
GridWidth = Mathf.RoundToInt(rectangle.Width);
GridHeight = Mathf.RoundToInt(rectangle.Height);
}
}```Like this, I'm forced to construct Spline prior to Grid, and Spline **must** have points in order for the bounds to have any side (else I get a 0 size Grid).
I can do it that way, but I dislike the sound of that type of dependancy. Could I instead have my Grid use a default value for size when no Spline exists (also when Spline has no points), but once Spline is valid the Grid begins to use it.
is this formula: Mathf.Sqrt(2f x JumpForce x 9.81f) only good for 2d platformers or good for any game(3d too)?
I cant see why it would only be good for 2D
It's honestly not good for anything in my opinion. It doesn't work properly for discrete physics, but it's a close approximation.
Why would 3d matter though?
because im working on 3d game
and im using continous speculative detection
What is the purpose of that formula?
found it on google
Again why would that matter to this formula?
bacuse you were asking?
I'm asking why you think it would make a difference
idk, i think im dumb now
I dont think its a bad assumption to think a formula that works with 2D jumping, might not translate to 3D
It's a bad assumption because the Y axis is common to 2d and 3d
do you want to specify jump height though? you said it's jump force
well, beyond that, the names barely matter
you shouldn't even care which axis is "up"
you should care about a gravity vector!
Well gravity defines what "up" and "down" are.
so as long as your gravity vector is aligned with existing world axis(es) then it'll be the same
I suppose I should say that you shouldn't think of a specific axis is "up"
that limits you to axis-aligned thinking
are you using a tilemap?
afaict grids don't hold stuff themselves, they literally just provide a grid
with a tilemap you can use this https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Tilemaps.Tilemap.GetTilesBlock.html
DAMN
exactly what i needed
thanks you ๐
is there a way, using the android autoconnected profiler, to get ANYTHING more specific than this?
I have no clue what object could possibly have a null reference, since it doesn't happen in editor for whatever reason
there's the logcat thing... in Window -> Analysis... I don't remember if it required a separate package
Android Logcat is the package, yes... it'll have ALL the logs
ah yesss!! that's exactly what I needed, thanks!
can i get the position also?
cause when i try there are not many functions TileBase provides and i can't seem to find the positions for ex
a TileBase represents a tile that you can paint onto the tilemap, not a specific cell on the tilemap
can't i make another class that extends the TileBase, then using Tilemap i make the array by converting GetTileBlocks into that specific class? Then i use GetTileData as an override to get the Vector3 position it has?
wouldn't that work
or i get something wrong?
Tile does not mean what you think it means
Tile isn't on the tilemap
it's on your palette
same for TileBase or anything that extends it
the tilemap has references to the Tiles on the palette
then how
do i get the postions
from the game itself
i don't believe a second it's impossible
you could use tilemap.cellBounds.allPositionsWithin to get a list of positions, then from those positions you can get the corresponding tile on the tilemap
it's a list of Vector3s?
for the tilemap i give the grid from the assets then using that list i will gather all the positions from the cells that were made in the game?
not sure what you're trying to say there
//class MapComponent
for(int x = 0; x < _grid.GridWidth; x++)
{
for(int y = 0; y < _grid.GridHeight; y++)
{
Map.SetTileColor(x, y, _tileCS, _testRT);
}
}
//class Map
public void SetTileColor(int x, int y, ComputeShader cs, RenderTexture tex)
{
GetTile(x, y).SampleColor(tex, cs);
}
```I'm doing this to have my tiles sample from a texture to set their color by sampling a texture. Does it seem like its a good idea to have the MapComponent have to loop over every tile to make them update their color?
What is Map and what does SampleColor do
Map stores private Tile[] _tileMap; and has a handful of methods to interact with the array
SampleColor runs a shader that takes the tiles position, and finds out where that is in a texture, the shader returns the color from the texture
currently theyre all black as I havent got the sample code working correctly. But when a texture is provided these tiles will change their color to match the texture at their location
You're running a compute shader to return a color to the CPU?
yeah, because I need to sample the texture
using the cpu to find the pixel color is even slower
I'll try it and see
but generally its not something I'd want to do
actually nah, its just going to be a headache to test it out, and besides I'd rather just do all texture related operations on the gpu, thats what its there for
can i just make a custom grid in my assets and give the script that specific grid to use for my tilemap?
right but you seem to be doing it pixel by pixel?
You should do one shader call for the whole texture
Thats mostly a result because im working with each Tile individually
I guess I could have the Tilemap sample the texture and return the buffer with all the different color values that it found
Hey, how can I prevent others from merging the main branch into the feature/bugfix branches?
Would this code work for getting from a tileMap the position of every tile?
public class Grid : MonoBehaviour
{
public BoundsInt area;
[SerializeField]
Tilemap tilemap;
public Node[][] openList;
void Start()
{
int xMax = area.xMax;
int yMax = area.yMax;
openList = new Node[xMax][];
for (int i = 0; i < xMax; i++)
{
openList[i] = new Node[yMax];
}
}
public void setGrid()
{
int i, j; i = j = 0;
foreach (Vector3Int tile in tilemap.cellBounds.allPositionsWithin)
{
openList[i++][j++] = new Node(tile.x, tile.y);
}
}
}
i wanna know if i work for nothing or not
how about testing it out
i got 0 clue of the tile positions
it would just spit out random numbers
success!
my Tilemap now just returns the array of colors that get applied to my Tiles
void SampleMap(uint3 id : SV_DispatchThreadID)
{
float2 uv = float2(id.x / (float)GridWidth, id.y / (float)GridHeight);
uv.x *= (float)TextureWidth;
uv.y *= (float)TextureHeight;
float4 color = Map[uv];
Result[id.y * GridWidth + id.x] = color;
}```technically the GPU *does* go pixel by pixel, but it does several pixels in parralell so its way faster than the CPU that just goes one by one
I wonder if its worth giving my Tiles actual world coordinates. Right now they only hold their XY position in the grid, but having a Vector3 of where they actually exist could be useful
https://hastebin.skyra.pw/sorehuwitu.pgsql is there anything wrong with this code?
what do you want to happen and whats happening
i want the enemy to wander when outside chase when inside
and whats happening
when i open the door first the enemy chases me but when i go inside i want the enemy to go back to wandering but it still chases me
so you need to add a limit to the .Chase() time then?
Are those logs getting printed?
yea
what u think could be wrong its so confusing
If the logs are printing it means that Chase/Wander are getting called correctly
So your issue is likely on the EnemyAI side
Why would anyone WANT to merge the main branch into another? Usually its the other way around, other branches get merged into main when ready - although maybe this might help? https://graphite.dev/guides/prevent-merge-without-review-github - essentially you may have to setup "rules" on the branch that require a "review request" that you can either accept or block before a merge can (or cannot) happen
Very often merge our main branch into features and staging to pick up upstream changes
Really? Interesting, I usually use the main branch as a "stable and shippable" version, where everything eventually gets merged into it, I seen some workflows that use the main as a "RC" (Release Candidate) with a similar idea where features are made from branching the RC, doing work, having it reviewed, then merging back into RC at the next milestone
https://hastebin.skyra.pw/xudotuhado.csharp this is my enemyai code
Debug it
Yes we both do this and also merge main into our feature branches frequently. If main hasn't been merged into your feature branch in a couple days your branch is considered stale.
Otherwise we end up with too many conflicts
im sure its not the enemy ai i debugged it it probably the collider in the other script but im not sure hwat im doign wrong
how do i switch between these at runtime? There seems to be absolutely no way but then why would this list exist?
It's actually chosen on the camera.
See the Universal Additional Camera Data component
Interesting, I havnt experienced that myself, though maybe its more common in larger teams or bigger long-term projects
note that merging a branch into another doesn't make it "go away"; it just results in a commit that has the the tips of the two branches as ancestors
(you can also just rebase so that it looks like your feature branch was just branched off from main, of course)
Our main branch has hundreds of commits each day yeah
Ah, interesting, that makes sense
Hundreds? So do you (or your team) make commits with "incomplete" code? Code that your still debugging or ended the day off with some errors youll "get to tomorrow"?
Nope. We just have a very large team.
It's always production worthy on main
Also we use mono repos so not everything is related
thanks!
Or part of the same deployable
hundreds of commits each day to main sounds horrible
I thought so too but we have a very good devex team so it works
well, I never want to see the history tree of a repo with hundreds of commits to main per day
i have a code for slope movement but everytime i jump i slide down a little
i really dont know how to fix this
Trying to spawn an enemy randomly to the left and right, but it ONLY spawns to the left. "spawnitem" always returns 1. even after 20 tries ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnmaster : MonoBehaviour
{
// Start is called before the first frame update
public static int spawnpoints;
private float clock = -1;
private int spawnitem;
public GameObject objectToSpawn;
public GameObject spawnLeft;
public GameObject spawnRight;
void Start()
{
spawnitem = Random.Range(1, 2);
spawnpoints = 20;
clock = 5;
}
// Update is called once per frame
void Update()
{
if (clock > 0)
{
spawnitem = Random.Range(1, 2);
clock -= Time.deltaTime;
}
if (clock <= 0)
{
clock = Random.Range(3, 7);
Debug.Log("Clock = " + clock);
if (spawnpoints > 0)
{
if (spawnitem == 1)
{
spawnpoints -= 1;
Instantiate(objectToSpawn, spawnLeft.transform.position, spawnLeft.transform.rotation);
Debug.Log("spawnitem = " + spawnitem);
}
if (spawnitem == 2)
{
spawnpoints -= 1;
Instantiate(objectToSpawn, spawnRight.transform.position, spawnRight.transform.rotation);
Debug.Log("spawnitem = " + spawnitem);
}
}
}
}
void Spawn()
{
}
}
try
spawnitem = Random.Range(1, 3);
change it in the start and update
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Random.Range.html
The maximum parameter is exclusive, so for example Random.Range(0, 10) returns a value between 0 and 9, each with approximately equal probability
the max value is exclusive when using Random.Range with ints. basically, your range is from 1 to 1 . . .
and change
clock = Random.Range(3, 7);
to (3, 8)
your code for spawnitem == 1 is the same as spawnitem == 2. why do you need to check for both?
I would try debugging your values, if your pretty confident those 2 functions are solely responsible for the issue, id add debug logs or breakpoints to check the exact frame of impact, and the state of all your variables during the frame before, the current frame, and the frame after to find out what is different between those 3 events
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
public class MyJobSystem : MonoBehaviour
{
[BurstCompile]
struct MyJob : IJob
{
public int a;
public int b;
public NativeArray<int> result;
public void Execute()
{
result[0] = a + b;
}
}
void Start()
{
NativeArray<int> result = new NativeArray<int>(1, Allocator.TempJob);
MyJob job = new MyJob
{
a = 5,
b = 3,
result = result
};
JobHandle handle = job.Schedule();
handle.Complete();
Debug.Log("Result: " + result[0]);
result.Dispose();
}
} what the role of NativeArray<int> is in this context?
If I have Foo<T> as a generic class, and SomethingFoo : Foo<Something> as a derivation
In Foo<T> is a reference protected static Foo<T> singleton, can I cast that to SomethingFoo ?
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What are you trying to do exactly. Because I might have a better pattern if it is what I think
not sure what you're going for here. care to explain?
I have a singleton archive class that stores references to scriptable objects of type T. it all works nicely.
Except that extra methods in the derived classes for extra functionality can't be accessed, because the static singleton instance is of type AssetArchive<T> and not the specific derived class name.
Yeah, use something like:
public abstract class Manager : MonoBehaviour
{
public abstract IEnumerator InitializeAsync();
}
public abstract class Manager<T> : Manager
where T : Manager<T>
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void Init()
{
Instance = null;
}
public static T Instance { get; private set; }
private void Awake()
{
if (Instance != null)
{
Debug.LogError($"There is already an instance of {nameof(T)} in the scene at {Instance.transform.GetFullPath()}. Replacing it.");
Destroy(Instance.gameObject);
}
Instance = (T)this;
}
}
Your instance would be of the type of the manager instead.
public class GameFlowManager : Manager<GameFlowManager>
GameFlowManager gameFlowManager = GameFlowManager.Instance;
@soft escarp THANK YOU, it works
And then I can do GameFlowerManager.Instance.DoSpecialThing(); if DoSpecialThing() is a method in GameFlowManager?
Yes
I'll give that a try!
Shouldn't this also have an extra type declaration for the type of scriptable object being stored?
And how would I do the Singleton = (T)this for that? As right now it's erroring on that
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Actually, lemme pastebin what I have for more context
I didn't post any large code block though?
I was asking for the code. If it is long use a pasta site
otherwise you can post it here.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Your constraint is wrong
public abstract class Manager<T> : Manager where T : Manager<T>
See what I used.
No no, I'm showing what the class I had is. Yours doesn't have a type constraint for the type of scriptableobject being stored, so I'm asking how yours would work with what I need to achieve
Yeah, then you would want to have an other constraint
With an other generic parameter
Because I have multiple of these archives, for each kind of scriptable object
I'll rewrite mine again to fit your set up, add in the constraint, and then provide the error I'm getting with that
public class AssetArchive<T, U> : MonoBehaviour, IArchive where T : UnityEngine.Object, U : AssetArchive<T, U>
Soemthing like that.
Also, I do believe you might want to use Addressable for what you are doing. You might not see it now, but down the line you are going to have loading/memory issue with what you are doing.
Would storing references to all my SOs be a performance hit on memory?
Yes
You are going to load all the SOs whenever you load the object that have a reference to the object that holds everything.
That means also all the image, meshes or animation that are associated.
As you are going with things, that would mostly be your entire game.
Wont matter if the game is small though.
In this case the SOs being referenced have no meshes, animations, etc. Just value type data, and some small sprites (32x32 max)
But, I should look at adressables anyways just to understand that system
Also, addressable is basically what you are doing at the moment.
You can load your asset by name or by label from anywhere.
Every call to GetAssets would mostly be a call directly to addressable
Example of getting all the statistics the game owns.
private Dictionary<string, StatisticDefinition> statisticDefinitions = new Dictionary<string, StatisticDefinition>();
private AsyncOperationHandle<IList<StatisticDefinition>> statisticsHandle;
public override IEnumerator InitializeAsync()
{
statisticsHandle = Addressables.LoadAssetsAsync<StatisticDefinition>("Statistic", (StatisticDefinition statisticDefinition) => statisticDefinitions.Add(statisticDefinition.HumanReadableId, statisticDefinition));
yield return statisticsHandle;
}
private void OnDestroy()
{
if (statisticsHandle.IsValid())
Addressables.Release(statisticsHandle);
}
Thanks, diving into the addressables documentation
I'm beyond brain explosion, yes I know there is a networking section for this but I don't think it should go in there.
I'm using a template in Unity that has multiple scenes that handle networking, and one of them named "Bootstrapper" for some reason. Before I press "Start Game" for multiplayer, it spawns the player, and for the level, it needs multiple spawn point so nobody spawns inside of each other, problem is, all the spawn points are specific to each scene, maybe I could fix it by moving the player spawning to be AFTER the scene loads but that's a lot of re-writing.
What should I do? I'm using Fishnet btw
This is a big project, and I've just switched from Godot, so please talk to me like I'm stupid
How it's structured after creating lobby and loading game scene
Hey, does anyone know why my Scrollview contents don't hide when overflowing? (Had to upload to drive, because the file was too big for discord)
https://drive.google.com/file/d/15yzEhqggnCEE9WkDc1AOPhho27fQsXxf/view?usp=sharing
is there any way to export a navmesh off mesh links to get the start and end pos i cant find anything even on the docs
what do you want to do?
I'm confused with what you wrote
Do you want to change the player spawn location?
Make sure the correct GameObject has a Mask, and for the objects that are overflowing make sure Ignore Mask is false
does CheckSphere work for a 2d space if i got my z 0?
cause it will take just a circle right?
yesssss
it works perfectly
thank u
didn't know 2d had these methods
It's a whole different physics library Unity uses called Box2D
hi guys, so im making a scope using camera renderer. The problem is, some of the objects cannot be seen through the scope (in this example, the green table is not showing in the scope even though i already iclude the culling mask to everything for the scope camera)
ahh nvm, found the problem
Hey guys, has anyone taken unity certified professional programmer exam? i am planning to take the exam and i had few questions about it..
nice! thanks for telling. can i direct message you? I just have some questions to ask
sure
okay
I took associate
I'm considering taking professional
that's good to hear
actually i am unable to find the exact structure of the exam, it's overall syllabus which it covers (it is provided in a high level way) and the learning resources for it. I saw that packt publishing has a nice book for the exam
I only know that mine was all multiple choice
i see.. how many questions?
60? 70? I can't remember
hmm and it was 1hr 45 min? did you do it on the pearson portal?
I did it physically
It'll definitely be shorter than 1h45 min
okay
You can leave when you're done
As long as you use unity a good amount you'll be fine
that is nice
i have made some games with unity so i should be fine then. any course which you recommend?
Course? I don't think there's any course to let you study in particular for the exam, as long as you know intermediate c# programming, ienumerator and jobs, unity UI, UI toolkit, old and new input system you should be fine
okay thanks a lot
