When creating a projectile system I came through the following point: lets say I have slow moving projectiles in my RTS game, server and client will spawn their own gameobject with a particles system on them. Projectiles are pooled, because reasons. Now I have let's say 200 different projectiles in terms of particle system. Is it a good practice to have 1 prefrab gameobject with 200 different particles system on them and activate the right one or make a pool for every projectile (go, ps combo)? Can unity handle that?
#archived-code-general
1 messages ยท Page 89 of 1
it sounds like there is some kind of mix-up, because if all of these things are indeed non-null, then there should be no error
also btw reminder this only started when make all the tiles children
an object in the list being null would not cause an exception to be thrown from the foreach itself
perhaps from an expression in its body, sure
(well, an object in the dictionary's Values property, whatever that is)
and just made sure, commenting out the stuff that makes it a child does fix it... so i think the issue has something to do with that...
have you done this by explicitly logging them before trying to use them?
if not, then go do that.
wym? like lookin at GridManager.Instace.tiles in a breakpoint on the foreachloop?
im super new to unity I'm lost on the terminology im sorry
from what you have told me, the foreach statement itself is throwing an exception
Debug.Log(GridManager.Instance);
Oh okay
and the same for the tiles field
if one of those spits out an empty log entry, then that thing is null
Oh the tiles field is returning null then.
well, there you go!
sounds like you didn't assign it
the solution to an NRE is always, always, always to check all of the things you're dereferencing on the line that threw the error
okay issue still is i dont get why cuz its public, it only stops working when i add this line "var grid = Instantiate(gameObject).transform;" even if I dont make the times children of it
kk
so, an inherent GUID is out, and I need to make my own key?
that's the vibe i'm getting here
https://gdl.space/usawidizeg.cs there is my whole GridManager script
It's saying you can either use the GUID from the AssetReference, or using the string "address"
and pathfinding for good measure(where i make the nodes) https://gdl.space/loqivikehe.cs
d'oh! that makes more sense now
I'm reluctant to use the address 'cos I might decide to rename the individual assets
wait could it be becuase the empty takes the name of the script?
It's been a bit since I used Addressables though so I'm not sure which one of these is more appropriate:
https://docs.unity3d.com/Packages/com.unity.addressables@1.21/api/UnityEngine.AddressableAssets.AssetReference.AssetGUID.html#UnityEngine_AddressableAssets_AssetReference_AssetGUID
or
https://docs.unity3d.com/Packages/com.unity.addressables@1.21/api/UnityEngine.AddressableAssets.AssetReference.RuntimeKey.html#UnityEngine_AddressableAssets_AssetReference_RuntimeKey
In the past I used RuntimeKey but IDK if AssetGUID is new
when i do cs var grid = Instantiate(gameObject).transform;
well, that makes a copy of the game object this component is attached to
OHHHH wait,
it won't have the dictionary on it
yeah i just realized that lmao
i mean to just make a new empty there
not a copy of the gameobject that scene is attached to
ah, that would do it
you'd get an NRE from the copy as it tries to function (without being set up correctly, presumably)
okay so final thing, how do you instantiate an new empty?
actually even easier i could just make this script the parent...
just new GameObject();
you're not allowed to construct a mono behaviour...but this isn't a mono behaviour (:
What does that mean?
you can't do something like
var rb = new Rigidbody();
that is valid C#, but will fail at runtime
however, that is the appropriate way to create a new empty game object
var obj = new GameObject();
(components must be attached to a game object, so it would make no sense to just construct them in the void like this)
Ah okay I get what you mean
Also most of the time I see people asking about like how to fix errors and stuff so I assumed not but would you also ask about like general tips in this chat? Like is there any way to make the two pastes I sent better, cuz I imagine they are pretty messy given I made them half following a tutorial while also trying to do my own thing with my very limited unity knowledge
what is xr?
it looks like I'd have to have an AssetReference field that points to a specific asset to use this. I did find that I can load the resource locations for all assets that match a label (e.g. "savePoints"), but I don't see way to go from IResourceLocation to the asset's GUID. I'm getting a big XY problem vibe from all of this...
after you are done with the current question please help ๐
XR is allegedly an acronym
it covers stuff like VR (virtual reality) and AR (augmented reality)
Outdated documentation I believe. There's cameraData.xrRendering.
ah, that make more sense
i was a little curious where the xr variable was meant to be coming from
so like cameraData.xrRendering.enabled?
No, xrRendering is a boolean. I'm not sure there is an xr equivalent anymore.
what do i replace cameraData.isStereoEnabled with?
I'm thinking I'll go with this scheme -- https://bronsonzgeb.com/index.php/2021/09/11/the-scriptable-object-asset-registry-pattern/
naming things really is hard...
2022
It does give you a good idea of the version, at least :p
it'd be really convenient if System.Guid was just serializable...
alas
Hey, to check if a point is in a cone?
radius is the radius of the cone.
maxDistance is the length of the cone.
a is the origin of the cone
b is the position of point in the cone
b is obtained from a raycast thus should always be in the range of maxDistance.
This angle doesn't seem to calculated properly.
Vector3 direction = (a.transform.position-b.transform.position).normalized;
float angle = Mathf.Abs(Vector3.Angle(a.transform.forward, direction)-180);
if(angle > radius) return false;
// in cone
return true;
you're on the right track, but you wouldn't compare that angle against the radius
compute the angle to the edge of the base
I guess you could completely avoid trig by making a vector to a point on the base, then computing the angle between that and the center axis
Wouldn't it just be:
Vector3 direction = b.position - a.position;
Vector3 forward = a.forward;
float angle = Vector3.Angle(direction, forward);
bool inCone = angle <= coneAngle;```
the cone is defined by a radius and height, so the radius needs to be computed
I'm assuming they just have the "tip" point of the cone (A) and an angle
like a typical "AI guard line of sight" situation
Not the standard mathematical definition of a cone
They did say radius but then compared that to an angle so not sure
i.e. like this
they have the smiley face (A) and the red point (B) and some angle
This is in 3D
same difference
wdym by "base of the cone"?
the flat part?
If so what does an angle from there to the point even mean?
the base would be the smiley face
Then this code will work
Why do you not normalize the direction?
there's no need to
Vector3.Angle doesn't care about the magnitude of the vector
It might even normalize the vector internally - in which case why waste the CPU cycles doing it twice?
apparently angle does normalize both vectors given
Im tryna make clone of hill climb racing but the tire is sometimes going inside the ground I am using an edge collider on Ground , I tried to tweak the damping ratio and frequency of wheel joint component but no clue
is that a wheel collider?
exactly - so don't waste time doing it yourself ๐
Thank you very much seems to have worked!
Nah Im using circle collider on the wheel and wheel joint on the parent object
Ah I've never used that one . hmm are you following a tutorial or are you writing your own script . Can you show it ?
Yeash , im following a tutorial https://youtu.be/E8lR59Yb2A0 this one by @tranquil ember
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon! - https://www.patreon.com/sasquatchbgames
Wishlist Veil of Maia! - https://store.steampowered.com/app/1948230/Veil_of_Maia/
Make a 2D racing game like Hill Climb Racing with this quick Unity tutorial. We'll even manage to ...
can you show your current script
!code
Posting code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
[SerializeField] private Rigidbody2D tire2 = default;
[SerializeField] private Rigidbody2D carRb = default;
[SerializeField] private float carSpeed = default;
[SerializeField] private float rotationSpeed = default;
private float _moveinput;
private void Update()
{
_moveinput = Input.GetAxisRaw("Horizontal");
if(Input.GetKey(KeyCode.R))
{
SceneManager.LoadScene("MainGame");
}
}
private void FixedUpdate()
{
tire1.AddTorque(-_moveinput * carSpeed * Time.fixedDeltaTime);
tire2.AddTorque(-_moveinput * carSpeed * Time.fixedDeltaTime);
carRb.AddTorque(_moveinput * rotationSpeed * Time.fixedDeltaTime);
}```
That's the code for driving car
Not sure about the wheel thing - but multipliyinh the torque by fixedDeltaTime is wrong
How come ?
because it doesn't make any sense
It's basically the same as arbitrarily putting / 50 there
I thought it was because I was multiplying the speed in the fixedupdate method hence gotta multiply it with that
no
also speed is a poor name for those variables since they represent a torque amount, not a speed.
aha makes sense
fixedDeltaTime never changes, its always just 1/50. Time.deltaTime is the one that checks the time since your last frame, but your code is in fixedUpdate so you dont need to worry about frame rate
i assume your speeds were set pretty high because of that
yep - remove the fixedDeltaTime and reduce the speed variables by a factor of 50
hi,
i'm trying to learn shader's code.
i have a question why do everyone writes the first parameter of each variable a string of description , do i need to do that in everyshader i have ?
example: _StencilComp ("Stencil Comparison", Float) = 16 , do i need to write "Stencil Comparison" as a first parameter for the float ???
cant i just do it normally like float _StencilComp = 16 ?
Ask in #archived-shaders
Two things you could try:
1 - change collision detection on the wheels from discrete to continuous. Not sure if that'll do it but it's worth a try.
2 - move the initial position of the wheels WAY further down than what looks natural. Take a look at some hill climb racing screenshots to see what I mean. Your car looks way too close to the ground. (Don't forget to update the anchor points when you adjust the wheel position)
Hello there, How can read the info of this column from the profiler? It seems like profile counter contains my answer, but I dont know which profiler category this belongs to and its counter name
is it even possible?
I would like to use it for debugging and displaying it on my screen
maybe look here
https://docs.unity3d.com/ScriptReference/Profiling.Profiler.html
nvm this is Dev Mode only
Yup, I noticed
I have used the get category method but fun thing is that the values it returns can not be accessed / dont appear when looking for that manually
is there a reason you wanna show GC at the player ?
this might work , did not test it myself tho
https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerRecorder.html @glossy basin
Im looking for some ideas for implementing this kind of system - in my FPS game, I have a script on the camera to detect objects with a IInteractable interface, but I want to add a system where if a player "dies" (reaches 0 HP) they instead get incapacitated and can then be interacted with in some way (similar to Apex or Fortnite, etc), im thinking of putting the interface on the player controller but then I have to check their HP every time a player looks at someone, and I dont like the idea that the interactor on the camera has to determine the condition for interacting, not every interactable has health, but they all DoSomething() - im wondering if there is maybe a better approach, would a new script using the interface, that is only enabled when the player is "dead" be the best option for this?
I am already using this for other data, but I dont know whats the counter name and category for retrieving the GC alloc info
I'm guess is there somewhere also the lookup seems to be done with a string
like a key for kvp or something
Yeah, it works by using string as a key but also looks for a category, I would say it is inside CPU category but the code doesnt actually have a category for CPU
Also I debugged all available categories and it displays categorioes that I cant even get
I never dabbled on this yet so I cannot provide much help sowy :
i've built my game, works fine in editor and no build error but for some reason the sound effect mixer is totally missing (no sound effects) and i have some blur effect and particle effect not showing at all from the build..? idk how to figure out with no errors
No worries, its not that important, just want to display some fancy values on screen :b
Hi everyone. I'm currently working on UI navigation. I've been using custom UI solutions with EventSystem interfaces. How can I make my own solutions compatible with the Unity's navigation system?
(the example code : https://pastebin.pl/view/979ac917)
Please configure your !ide first
๐ก IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I just opened the rider, it wasn't fully compiled yet.
I also shared the full code in pastebin.
Hey, not entirely sure if this is the right channel for this, but...it feels like GPU instancing doesn't work.
This is not the right channel no
#archived-shaders or #archived-urp or what have you
#๐ปโunity-talk if it doesn't fit those
Does Anyone Know Playfab REALLY Well
I have this script and my item ids are exactly correct the playfablogin catalog is Catalog 1 which is the catalog name and when i press it it says Error: Invalid Input Parameters
PLEASE HELP https://hatebin.com/nbmtqfsvlg
!code
Posting code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I want to create cheap visuals for debugging that I can see in play mode and later replace. Should i use mesh generation?
Depends what kind of visuals you want
there's always Gizmos
or just using basic cubes and stuff
yo i have a problem with unity where you have a gameobject in a dontdestroy but when you get back to menu you get 2 of them. is there a way to say that i dont want to spawn another one while ingame?
yeah look up the singleton pattern
it's very common
(that's why it's called the singleton pattern - you only want one of them at a time)
aight aight tnx
what abt my problem why no one help me
Maybe nobody knows playfab well
oh
i just really need help
i have a game on the quest 2 store and when u uninstall you lose everything and it rly annoys ppl
ur better off asking on the playfab discord
well, yes, when you uninstall all local data is lost, so you need to look at a server side data save solution
i've done mesh generation to visualize the path swept out by a hitbox
wasn't the worst thing in the world!
Is there an equivalent to Scriptable Objects in C#? Like making an Abstract Class or something? I need some help. Essentially want to do the same thing as a SO. Where I can declare some Variables and then set them for each new one made. But im stuck.
Im making a JobBase and then making the actual Jobs inherit from Base. But idk what im doing I guess. Never comes out right.
public abstract class JobBase
{
public string JobName { get; set; }
}
public class Job_Warrior : JobBase
{
JobName = this.GetType().Name;
}
Basically the above, but I can't override the JobName, not sure what to do
JobName is a property here, and it's not marked virtual
you can do something like...
public abstract class JobBase
{
public virtual string JobName => "No Name Job";
}
public class JobWarrior : JobBase
{
public override string JobName => "Warrior";
}
you can't assign to a field (or property) like that in the class declaration at all
you can provide a default value for a newly declared field, but it can't use a function call like that
I see, now. Thank you very much!
hello there, I am using this code here Profiler.GetAllocatedMemoryForGraphicsDriver() / 1073741824.0 for retrieving the current graphics card usage of my project, however it just increases every time and doesnt decrease when I for example remove objects from the scene, is there any other line of code to get the current graphics usage?
i use this sort of pattern for things like move speed on one of my state machines
each state has a property that says how fast the player can move
and i just override it as eneded
removing an object from the scene will not immediately free up the memory that its renderer was using
also, note that this is just "allocated memory"
How long does unity take to free up the memory used by that object if it was removed?
I noticed this , but couldn't find any other method for retrieving the current graphics usage.
I used UnityStats.usedTextureMemorySize which displays a more accurate value, but it only seems to work when the profiler is opened
If we're talking about RAM, it's gonna be cleared by the GC if there are no references to the object and GC is allowed to collect it. If we're talking GPU memory, you probably need to resource that occupies the memory.
As for what you profiled, I'm not even sure if it's either of those.
I just want to display useful debug info of my project on screen, but want to make sure the information is actually correct and not some random numbers
in this case is GPU, my ram stats seem to work well
Ahhh, makes sense
I imagined It would go Up and down
there's gonna be a lot of slop there
depending on content
i'd just sanity-check by adding a bunch of 4k textures to the scene and making sure the number goes up
Im gonna try and check, thanks
but as I said using the UnityStats shows a more accurate representation, and the value never goes up as the current method im using
this is how my stats, on the graphics card part it uses 2GB when I am using a single texture
ofc it goes down when restarting the scene, but still, its quite a big number considering my texture is a texture atlas, 32 * 32
There's more than just your textures involved in rendering. For starters, there's the render target, and there could be other intermediate resources that occupy the memory as part of the rendering process.
And again, I'm a bit sceptical wether GetAllocatedMemoryForGraphicsDriver() corresponds to GPU memory exactly.
i do have to wonder if that number is very useful for systems that aren't sharing memory with the gpu
"for graphics driver" is the funny part
Makes sense, I supposed this too
The API says it corresponds to it but I do share the same feeling
Lmao, I will probably removed that, I have seen that some version of Minecraft that use shaders do not work on certain driver versions, so I wanted to include the driver name in case somebody faces the same issue, but since this is Unity and not Minecraft, I assume that's most likely to not happen
oh no, I just mean that the function name makes me a little suspicious
The forums seem to confirm that it corresponds to the GPU memory though.๐ค
Ohh I see, then it is the right value, thanks!
Does the function OnValidate of the BaseMeshEffect only runs on the editor mode ?
Do i need to wrap it under #if UNITY_EDITOR ... #endif ?
Hello there, I am wondering what approach I should take for defining block stats (in a performant way), I currently have a voxel game, and the way I am defining my blocks array is by simply using an enum, and then storing their values there (i.e BlockType.Air or BlockType.Stone) (since enums are ints under the hood), now I want to implement a survival destruction system where the blocks have certain durability before breaking, so I though of rebuilding the array and instead of enums, use structs which contain the corresponding block stats, however I am not sure about how performant this could be, is there any better aproach to this?
I also though of just using a singleton or static class that contains all block data and whenever I try to destroy a block, just go to that class and get the block thougness and such. What is the best approach?
not duplicating the data a few thousand times feels like the right move
enums are already structs, just smaller ones.
If you need to add more data, a bigger struct with multiple fields seems a good way.
:0
So it does not affect performance to have a struct array with multiple variables on it?
compared to having enums which only contain a single variable / just an int and not int, float, etc
That would be less data
less data = faster
but if you need the data
you need the data
I assumed so, thanks
i would store the ID (and only the ID) on the block, and then have a dictionary or something that holds the block data
Seems like the second option I though off
there's just no reason to have every single stone block say "I am a stone block and have a toughness of 10"
Why not just skip the "block" thing altogether then and just have the Dictionary
Oh wait I see what you mean
yeah you don't need durability for 99.9% of the blocks
I'd store damaged blocks as a separate, sparse thing
yeah, after all the blocks will always contain the same values
assuming you can slowly destroy a block, like in minecraft
in minecraft you can only partially destroy a single block at a time
^
I see, I will take this into consideration
So it's not even a dictionary
yeah, so that might even just be a thing the player keeps track of
overall, you don't want one gigantic array of blocks loaded at all times
there's a lot of minecraft tutorials and how the chunks are stored
i'd do it in a data-oriented-design style
yeah, I have seen some vids on it, never actually finished them though ๐
although I'm not sure how I'd actually render the blocks and give them collision
I plan to migrate the project to ECS later on, I have to still learn few things about it that I was not able to solve on my past project which was ECS deformation
Now that you talk about it, in the case of voxels I assume it would be better to compute the mesh in the GPU rather than CPU right? I am using Jobs and burst for generating my meshes, this is already very fast, but just wondering if I can speed up the processs for low end pcs
Just not quite sure wheter or not Compute Shaders can be any better compared to burst compiler
They can. It depends on the job that needs to be done. But if it's a task that needs a lot of similar small parallel jobs(like a million), a compute shader would excell.
The more parallel jobs there are, the more CPU would lose to a GPU
Hmmm, I guess I should move my mesh generation to compute shaders instead , especially for the fact of parallel processing, I assume GPUs are specialists on that
Currently my mesh generation runs on a Ijob instead of an Ijob for, I tried to generate the mesh in parallel but for some reason my data was always wrong when using parallel jobs giving degenerated meshes ๐
I assume compute shaders wont have that issue right?
it seems like my job was losing data on the go when using IjobFor and native lists as parallel writer
Yeah, parallel mesh generation would require some adjustments, since triangle order is important for meshes.
these were the results of our beloved artist IjobParallelFor
They will, unless you adjust your algorithm to not rely on the order of the job completion.
Ohhhh, so that might be the problem with my parallel job, probablu
Probably.
I had 3 separated jobs, one for generating vertices, another for tris and another for UVS, I set the dependency of each to be the previous job handle
Yeah, vertices generation would probably need to be done together with triangle generation, since they're interconnected.
I see, well, I will do some research on compute shaders or maybe try to solve the parallel job issue
Look up race condition. That's basically the issue that you were experiencing.
Very common in parallel programming.
I guess I can pull info from gpu back to cpu right? I mean for retrieving vertex positions and generate colliders
You can, yeah.
Ah yes, thats my doom, most of the times I code on parallel stuff I happen to get some race conditions
Great! it makes the task easier
@cosmic rain sorry for the ping, but just curious, is it okay to use for loops into a parallel for or it just misses the point of IparallelFor by itself? the reason I splited triangles from vertices job was because their resulting arrays have different lenghts
so using different jobs would make their index value depend of the lenght I specified rather than having an extra loop inside
I mean, if a for loop is part of a logic within the job, it's totally okay to use it. The issue arises usually when you process some order sensitive data in parallel. You can guarantee the order when the jobs are executed in parallel.
Ahhh alright, but wont having a loop inside be repeated the amount of times the index is ?
You could process 3 vertices and 1 triangle within one job. This way the difference between the collection lengths doesn't matter.
like wont this be doing unncessary processing ?
alright, Im gonna give it a go!
Depends on your loop. I'm not entirely sure what exactly you have in mind.
Again, hard to say anything without seeing the code.
I just want to convert my current job into a parallel one instead, since currently my job has just one loop for checking block data and another loop inside a function that sets the triangles based on the faces count found
I will show the relevant code instead of the full code, as the other part is just UV stuff
1 sec pls
Do note that the uv code might also need to be adjusted.
Yeah, I am certain of it, but since it is running into a separated job it should not be hard to do
You could take your for loop iteration and run it in a parallel job.
The main issue is that you're adding the vertices.
vertices.Add(vert + blockPosition);
And relying on them being ordered when creating the triangles.
In parallel you don't know what vertex is gonna be added first. So you can't rely on the order there.
If you do want to rely on the correct ordering, you'll need to assign the vertices to the correct index in the collection manually.
Ohhh, so thats why my triangles were always degenerated
Also makes sense why I was losing data over generating vertices in parallel, the array lenghts would always be lesser compared to the Ijob vertices lenght
Or you could have a Triangle struct that contains the 3 vertices. You generate the 3 vertices, set them to the struct and append it to the Triangle collection. Then you could run a synchronous job that loops the Triangle collection, adds the vertices to vertices collection, while also constructing the triangles(indices) collection.
this sounds more reliable, this would assure me the order will remain the same
I will take that approach for sure
now, I have seem there is an extra API that lets you process mesh data into a job which is the MeshData API, but I guess in this case I should just add the vertices in the main thread in order to not lose data right?
or should I just stay with standard mesh system
I used it into a previous project, it is pretty hard to setup, and all the examples I could find of it rely on already generated meshes rather than procedural meshes
yo is there a way to make something run when a new class is made? like say checking if one of it's parameters are null and then setting it to something?
Either would do. I'm not really accustomed with the MeshData API, so can't really recommend anything about.
Class? Or an instance of a class?
Alright, thanks you so much for your time on this topic! I am kinda a beginer into jobs and procedural generation
instance of a class! sorry I wasn't sure on the terminology
You could use OnValidate or something. I think Reset might also be running when an instance is created.
like say I'm setting list "PartyMembers" via the unity inspector, but one of the things that make up each entry in party members is not serialized so i can only set 1 half of it, Id like to check if that other half is null and set it to a default
ill try those
this should be better context, its saying OnValidate will be unused
onvalidate is mono
OnValidate is only a thing for MonoBehaviour
AH okay, my point was is there a way i can do it for Non MonoBehaviour things?
Using a custom property drawer
Or validate it from the MonoBehaviour that serializes it.
this is contained on a ScriptableObject
Then from the ScriptableObject
could just make the class a mono and implement your own initializer
You could also probably add default initialization in the constructor
or that haha
you should ask in #archived-shaders or #๐ฅโpost-processing
There's no way to do that from the C# side. You'll need that handled in the shader, although, it's gonna be tricky either way.
Both things yall said are beyond my knowledge level so imma just make a script OnValidate() on my scriptable object that looks at each PartyMember in it's list of PartyMembers and checks if the stats are null and if so sets them correctly
Hi, I'd like to ask if there's any way to improve model smoothness? I've tried increase anti aliasing and enabled auto smooth in import settings.
Is there a way to see what force value is applied to a rigidbody (player) in the collision of another rigidbody (cannonball)? Or is there a better way to do what I am trying?
Im trying to limit my players move speed to a max which is easy, but this comes with the effect that the max gets applied even when the player gets hit with extreme force. I want them to ragdoll in such a case and still get tossed around fast.
Desired interaction: player walks around with max velocity=10, cannonball hits them and player max velocity=40 while they ragdoll
But i cant just check collision with cannonball and set speed = 40 or else the player can touch one on the ground and get a massive speed boost. So i was wondering if I could check what force the cannonball would apply to the player, and conditionally adjust the max speed based off of that.
(Or maybe theres a way to just have the input apply a max of 10 while not directly limiting rb.velocity which is what im doing rn)
Can someone here help me?
I have no idea how to fix this and I don't see anything wrong with my code
!vs
Visual Studio guide
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)
Do I install the top one or the bottom one?
You don't install either. You click the one that relates to your situation and follow the instructions
After it's configured then your problem is likely that you have accidentally duplicated your script
THANK YOU!!! I just now looked for and found the duplicate!
You just saved me from a massive headache!
You still must configure your IDE. It's extremely painful to code without it, practically a waste of time
Im trying to get the edge of a sliders fill rect but no matter what the slider value is at the fills AnchorPosition stays at 0,0. I assume this has to do with my anchor/pivots but I cannot move those as the slider is dependent on them to keep the fill within bounds of the background. Can anyone advise on this?
Okay then
What is it that your trying to do? Why do you need the sliders rects in this way, as oppose to just using a rect transform without a slider component?
I mocked up what I am trying to do in code in below image. As the bar progresses, checkboxes appear. I wanted them to instantiate and set location to the rightmost edge of the fill rect as the slider val increases
hay is this a good way of doing specifically the updateParty and and ReplaceMember methods?
I'm fairly new to unity and just trying to learn if there are any ways I can optimize or write this sorta thing more efficiently
if it's your first project I suggest you just continue on if it works without trying to optimize
Throw your question into #๐ฒโui-ux since this channel usually moves much quicker
probably get an answer in the morning
alright ill copy paste it there
Fair but I've been told that before by a friend when I asked a similar question about taking inputs, but I would really like to learn better ways of doing things sooner than later so it's frustrating to hear.i just feels like this could be done better and faster tho I guess I'm falling into that "taste clashing with skill cuasing you to over perfect everything leading to you never finishing your art" thing so I'll accept your advice
You can always refactor your code later. You're not likely to run into performance problems either until you much later (most of the time it's some unity feature and not your scripts), so I suggest keep going with whatcha got.
If you did want to use a slider for that, it might make more sense to do percentage math instead to position the icons based on the value of the slider between 0 and 1, or progress / max - alternatively, you could do the calculations yourself with just a rect transform, taking the someRect.rect.bounds
hello there, I got this smooth mouse look effect, but whenever I walk and look around , the movement feels very glittery
My movement script manipulates rigidbody velocity instead of adding force to it but I am not quite sure if this is the cause of the problem, the movement script runs on fixed update, I am almost certain the mouselook is the issue
I always struggle with this too. I usually solve it by just moving a "head" object parented to the rigidbody and moving the camera to that position and rotation in the LateUpdate method.
Also, does your rigidbody have interpolation on?
Ohhh, let me try this
yes, I have my rb on interpolate
I also read online something about possibly using the screen refresh rate to smooth the camera rotation? I can't find it rn tho so I'm not sure, but maybe you can.
this sounds interesting but I guess it would make glitter on low refresh rate screens or maybe not ๐ค
yea not sure, I never did it but maybe it could be helpful
how would I randomly generate an Island ensuring there are a certain number of structures on it at all times
Somehow like this:
while (spawnedStructures.Count < structuresNumberToSpawn)
{
if (!isThereASpaceForANewStructure ())
GenerateMoreTerrain();
SpawnStructureOnEmptyTerrain ();
}
There are plenty of videos about map generating in Unity that have more detailed examples.
So I have a basic project that was working fine but when I uploaded it to WebGL a few things broke, I've gotten the basic in editor version working again but now my instantiation for projectiles is no longer working. There's nothing wrong with this function from what anyone can see right?
Rigidbody bulletClone = (Rigidbody) Instantiate(bullet, transform.position, transform.rotation);
bulletClone.velocity = -transform.right * bulletSpeed;
ammoCount(-1);
string ammoValue=magSize.ToString()+"/15";
magText.text=ammoValue;
}```
Everything but the Instantiate is working as expected
How to multiply quaternion by time delta?
basically I have some rotation
I want to apply to other rotation
but I also need to differentiate it by delta
Maybe a Slerp? someRotation = Quaternion.Slerp(fromRotation, toRotation, normalizedTime) or one of the other functions in Quaternion
this is rather expensive
first you gotta achieve total target rotation by quat mul
then slerp it
Well if you know the rotation you want you can pass that, if you want it progressively some value ahead of what it is (a direction), you could add that, maybe with Quaternion.Euler
nah, this is overkill. Hopefully there is a simpler alternative
Can someone please tell me why "Private" is underlined red?
private void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
stream.SendNext(BubbleSpeechObject.active);
}else if(stream.isReading)
{
BubbleSpeechObject.SetActive((bool)stream.ReceiveNext());
}
}
hover mouse over, IDE should tell why
I am using a tutorial and it has private there but its not underlined red
I might not fully understand your scenario, if Slerp might be too expensive for what your doing, what kind of alternative are you looking for? Another way that comes to mind might be to cache a Quaternion and calculate w
in pseudo code it'll be somethng like this
private void Execute(in ConstantRotation rotation, ref LocalTransform tf)
{
var deltaRotation = rotation.rotation.value * delta;
deltaRotation = math.normalize(deltaRotation);
tf.Rotation = math.mul(deltaRotation, tf.Rotation);
}
Hmm, sorry im not sure the best approach for that, if you can convert rotation into a Vector, you could do vector multiplication after you normalize it, then convert it back into a Quaternion to apply, its another option though maybe not exactly what your looking for
Has anyone used 2 Firebase apps in a singe Unity project? Is this even possible?
Guys i fixed one thing but now this isnt working here is my Update function
private void Update()
{
if (photonView.isMine)
{
if (!DisableSend && ChatInputField.isFocused)
{
if (ChatInputField.text != "" && ChatInputField.text.Length > 0 && Input.GetKeyDown(KeyCode.Slash))
{
photonView.RPC("SendMessage", PhotonTargets.AllBuffered, ChatInputField.text);
BubbleSpeechObject.SetActive(true);
ChatInputField.text = "";
DisableSend = true;
}
}
}
}
And here is the error
NullReferenceException: Object reference not set to an instance of an object
ChatManeger.Update () (at Assets/ChatManeger.cs:27)
It brings me to if(!disablesend && ChatInputFeild.isFocused)
looks like something is null in your code, probably ChatInputFeild
Ill show you my Awake function
private void Awake()
{
ChatInputField = GameObject.Find("ChatInputField").GetComponent<InputField>();
}
to be 100% sure that you don't miss the reference, just set it from the editor
just because the statement is in Awake does not means it actually works. Break the statement down and check which part is failing
Its was a TextMeshPro one
I am replaceing it with a legacy one
But i cant put it in the editor
It wont let me
you will need to change the type of ChatInputField to the correct one
Wait nvm i got it
Anyone here familiar with GameAnalytics SDK? Does it require only to create its premade GameObject or you have to write up some scripts in order for it to work?
About UI management, do you think it's better to group all in one manager class or separate into different small classes?
in my most recent game, I have a single InterfaceController, but its job is strictly to turn smaller classes on and off
one of those smaller classes is GameMenu, for example
roughly equivalent to this menu screen from Nioh
and then each sub-menu is its own class as well
e.g. Equipment
that seems a good approach
yeah, it means that each sub-menu can exist on its own if needed
NullReferenceException: Object reference not set to an instance of an object
Yup tried making the the from discrete to continuous and I lowered the carspeed and that worked for me so thanks for the help guys , @tranquil ember , @potent sleet , @lean sail , @leaden ice
I've installed the LTS unity editor for 2021 [ver 2021.3.23f1] and i've created a blank 2d project and this error shows up, can someone help me?
this is a bug with the Version Control package
if you aren't using it, then you can remove the package
thank you
hi can someone please help me out with my project I'm really stuck at some things pleasee
Anyone here having experience with GLTF2?
If so... can i also e.g. export prefabs in unity to GLTF2 to load them at runtime (e.g. from web) later?
And what about components on such prefabs?
you have not told us what you're trying to do, or what the problem is...
I have a detection app that detects people moving in a certain area, it assigns person ids to the person and send to me in unity, I instantiate gameobjects that get the current positions from server and move them from left to right and right to left, basically trying to immmitate their movements in a 2d scene.
Right the gameobject leaves multiple clones behind it that stay on the screen without any purpose I want to destroy them.
somnolent: hi I'm stuck
refuses to elaborate
Congratulations
that joke really blew just cuz of my wifi
okay but what's the problem you are having. You explained what you want to do, but what part of that is not working?
okay, so the problem is
my gameobjects starts flickering sometime
and whenever the id changes from the detection model it still sends it to my unity
and because of that clones are created but those clones stay on the screen
i want to destroy them
and make the whole thing be smooth
like if a person comes the gameobject should move according to that and then be destryoed when it is outside of the screen
the only thing is I dont have much time
so stressed about it since last few days
and have to make it work
so every time the detection model loses track of a person, the game object gets left behind
and then when it notices them again, a new object is created
perhaps you should have the object keep moving with whatever velocity it had when you lost track
can I show you through video
and then, when detecting a new person, it should see if there are any "lost" objects near their position
yes
what kind of data are you getting from the detection model?
does it just send you a list of IDs and positions on a regular basis?
Is there a way to revert all changes made since I opened the Rider IDE today? (I did not git commit)
maybe if you mash undo a bunch
oh wait
sorry, I misunderstood: you are using Git
nono
I mean I am using Git but I didn't commit today and yesterday, but I want to revert back to when I started today
Rider might have some kind of file history you can use. I know VSCode does.
I can click on one of those to go back to an older version of the file
It isn't complete (like I can undo only 30 times)
hi sir
While it seems to know all the changes I did, when I press to for example the first change it says that there is no difference...
Hello there, does anybody have the definitive rigidbody character movement and a smooth mouse look? My scripts seem to have conflict with each other resulting in glitter movement
glitter?
yes, when walking and looking around, the movements seems like stuttering
from what I can see, the mouse look is the issue here
jittery you mean. Glitter means something else entirely ๐
Sorry, im not familiar with some english terms ๐
So yeah, my mouse code seems to cause this issue, when I disable it and move around, everything looks as expected
Jitter happens when the movement is not updated at the same rate as the rendering.
*movement or rotation
should I handle the mouse look in fixed update? doing so results in even more jitter
One common cause is if your movement is physics based(updated in fixed update) and the interpolation is not enabled/working.
No, that's one case that would cause the jitter
right now it uses rigidbody on fixed update, and interpolation is set to interpolate, but still same result
I modify velocity instead of adding force
Even if interpolation is enabled, it doesn't mean that it's working.
If you're moving or rotating it via the transform, for example, that would break the interpolation.
First determine what conditions cause the jitter
Ahhh, I am rotating modifying the local rotation
you should be using addForce
Well, that's gonna break interpolation for sure
what is the advantage of it over velocity? I cant really remember why I made this script this way (made it 2 years ago I guess)
Ah maybe it was because my character would just slide when using add force
changing velocity directly might run into issues where u cancel out other movement like if u get tossed really fast
then u gotta set a max speed, but im actually having issues with max speed taking not letting me get tossed fast either so idk what to suggest there
Yeah, according to what you said it should be the cause, I just found outh rb has a method for setting rotation
Im gonna try that out
Changing velocity is one valid way to implement movement. You just need to know the implications of using it.
the solution I took for this was simply enabling default velocity when character is not grounded, and my own velocity when own ground
so I dont face that problem
Using velocity gives you more control over movement but you have to assign the velocity correctly to avoid canceling any outside force applied to the object
Using force takes care of applying it to the object but you have to limit (cap) the amount of force over time as it will continue to increase . . .
How does addForce work anyways?
If i add force inside fixedUpdate, the velocity doesnt change until Update from what i tested. So idk how to set a max speed inside fixedUpdate as well, i run into issues where the max speed gets set to 8 but since the force seemingly gets applied in update, it becomes 8.16. The 0.16 is because thats 8 * fixedDeltaTime
Yeah well made kinematic controllers can be amazing, but as your everyday Unity fiddler I can tell you that mine tend to be horrid. lol
If you wanna make your own controller it's usually easier to just use forces.
There's a pretty popular free kinematic controller in Unity Asset store, though. iirc.
The velocity change is applied in the physics simulation step
which happens right after FixedUpdate
it does not happen in Update
Implementing rb for rotation fixed my issue, thanks!
is there a way then that I can limit the velocity from movement before update()? The message i replied is the issue ive been having
Yep, regardless of where you set/ assign the velocity, in Update or FixedUpdate, it won't take effect until the physics step . . .
Do the math yourself and apply it to the RB velocity instead of calling AddForce
You either do feedback loop where you apply different force based on how close you are to max speed, or use change velocity mode of adding force.
Yeah, you can also calculate how much force needs to be applied to reach certain velocity.
I was thinking of decreasing the force as i got near the max speed, but then turning around would also be really slow. I might just try changing velocity then in my move function and only limiting it there. That should allow my character to hopefully get ragdolled at high speeds
thanks still, i actually did look at that execution order but i didnt really understand where the addforce step was done. I thought it was done at the same time as fixedupdate
in practice, you reach a 'max speed' because air drag + ground friction = forward force
(or just air drag, if you're airborne)
I mean, adding force is almost the same as setting velocity.
Ignoring the mass of the object, if, let's say you want to set Velocity of 2,0,0 when the current velocity us -1,0,0, you just add impulse/velocityChange force equal to (3, 0, 0)
or you can do that with Force(default)/Acceleration mode by also dividing(I think) that vector by fixed delta time.
right, since applying 50 newtons of force for 0.02 seconds will get 1 kg object moving at 1 m/s
of course, you might as well just use the appropriate force mode and not deal with the extra step
both of these have the same effect:
rigidbody.AddForce(Vector3.forward * 1f, ForceMode.Force);
rigidbody.velocity += Vector3.forward * (1f * Time.fixedDeltaTime) / rigidbody.mass;
```so you can use velocity if you know how to apply the force (dependent on force mode) . . .
i guess then my whole error came from the fact that the velocity was changed later than i thought
ive been fine tuning this rigidbody movement for too long at this point
thanks everyone for the advice and specifics, it was really helpful ill try to get it working from here
the thing is, whichever method of physics movement you choose, you must use it for everything, don't intermix . . .
For coroutines, is it possible for a coroutine function to have a waitforseconds and waituntil albeit separated by say an if/else block?
sure
There are no limits to the control structures you can use in a coroutine
i have a 2d project and i want my player animation to change depending on the cursor position(red circle = normalized vector). like this:
the problem is i don't know how can i write this with code. i wrote some code but that doesn't work. there is any better way or my coding skills are not enough?
Use Vector3.SignedAngle to get the angle relative to -22.5 degrees, then divide that number by 90 to get a value between 0-3
(and FloorToInt)
Hello there, can anyone help me with this warning message "Unable to find player assembly: C:\Users\JURAJ\Unlock And Explore the underground\Temp\StagingArea\Data\Managed\UnityEngine.TestRunner.dll"
warning is annoying, it seems to not affect game after building it, but still I want to fix it.
maybe delete that temp folder?
I don't need that folder?
Would this work?
thanks
Gathering opinions. Has anyone found a newer or better endless procedural terrain tutorial to follow than the Sebastian Lague ones that are about 7 years old?
Welcome to this series on procedural landmass generation. In this introduction we talk a bit about noise, and how we can layer it to achieve more natural looking terrain.
A quick summary:
'Octaves' refer to the individual layers of noise.
'Lacunarity' controls the increase in frequency of each octave.
'Persistence' controls the decrease in ampl...
Can you give me an example of this? I read the documentation but I don't really understand how this works
just delete the library folder and run the project again
do you know what could be causing this warning since I see a lot of people had this same warning here
procedural generation always precedes from noise algorithms so, it is really up to you on how to implement those noise functions
keep in mind that there are a lot of noise functions to mess with so you can get some different results depending of what you are looking for
Agreed. His tutorials go into LOD, endless terrain, threading and more.
Oh hey I knew I helped someone with this same question recently:
#archived-code-general message
that's for 3D
you might have to adjust some of those direction vectors if you're in 2D or whatever
but that's the gist of it
I started wondering if it was still relevant cause I saw Unity does LOD natively now and he writes a script for terrain colors but Unity now lets you move the array through drag and drop.:/
thank you
the concepts of this video does still work to this , but you may want to upgrade some of the stuff he used back in the day because as you said, unity handles a lot of it by itse;f
Not sure about LOD (I did not watch the full series) but I dont think unity does LOD for procedural terrains
does anyone know of any resources where I can find specifics about how to make grapple points?
for 2d specifically but idk if it matters
also, If you are curious about some noise patterns for procedural terrain, you can watch the GDC talk of no mans sky where they explained what kind of noises they use and their effects on terrain
that didn't really do the job :/
Weird, did you delete this 2 folders?
it's in library I think
delete library folder then, make sure to have your project closed when removing these folders
yes ofcourse
i have a gameobject, and a child gameobject. when i rotate the parent childobject, i want the childs rotation not to change with the parent ones
is that possible?
then don't parent it
that's whole point of parenting
You could apply an equal and opposite rotation to the child... or a Rotation Constraint component... but it would be better to not have it as a child
so set the transform.position to follow the parent transform without parenting
so theres no build in way to lock it
alright...
I would unparent the child, and make it follow the parent position instead
Or consider using a common empty game object as the parent of both. Translate the common parent to move them both, rotate the child for independent rotation.
unparent the object, rotate the object and then parent it again
not a real question but just asking for feedback, is it me or unity default gravity feels like moon gravity by default? It may only be my perspective but I feel like the actual gravity does not feel as accurate as it is supposed to be
how big are your objects
small, a player
scale of 1, 1.5, 1
a human is about 1.75 meters tall
sadly I still get an error
The overall feeling is the same, as I said I may be me, maybe playing arcade games gave me a different perspective of how gravity in games should be, but thanks for the info
average person is about 1.75m tall and can jump about 0.20 meters in the air. If you have a capsule scaled at 1.5 on the y axis it's going to be 3 meters tall and you probably have him jumping several meters in the air.
The extra large size of your character plus crazy jump height is probably leading to the feeling of moon gravity
try jumping irl
The large size contributes due to the "godzilla effect". Large objects tend to seem to be moving very slowly but it's a trick of perspective and distance and how your brain interprets things.
indeed
Ohhh, interesting concept, didn't know it had that name
idk if that's a real name or something I made up lol
also I just googled it and - don't google it ๐
Lmao, but I can tell the name should be similar lol
I wont even ask what u found....
unity also doesnโt take air resistance into account with falling objects just like the moon ๐
I already knew this but I didnt thought it would make games feel different
I've imported com.google.play.appupdate package and I've start getting this error in console. I find out that if i enable all conection over HTTP, then there is no problem. Is there a way to only enable google one?
did somebody mention me? lol just saw a ping
I have found a really weird bug. My variables in the GameManager script start out with assigned values. E.I. private static bool example = false, when output with the debug console at the start of the awake function, is true. This problem persists even if the GameManager is the first in script execution order. The weird part is it only happens in builds of my game. The editor works fine. The problem variables are also static, if that matters. Does anyone know if Unity does something special with the GameManager script that is causing this, or something else?
If the variables are static if theyโre ever changed in a different scene they donโt reset when changing scenes
So if you play two separate scenes in the editor, itโll work fine, but if you transition scenes itโll be the last value it was set to when it calls the Awake function
Perhaps thats the problem?
It is the first thing that happens in the game. The Debug.Log reveals the awake function is only ran once. No scene changes occur.
Well somethings changing it bc itโll compile as false so it wouldnt ever be true unless something changes it, and it cant be serialized since its static so itโs not unity doing it.
Without any code to look at its kinda hard to do any debugging
It isn't my code. I added it as a testing variable after my static singleton was doing the same thing. It is only referenced in it's initialization (what I posted before) and it's Debug.Log.
private static bool isGameManagerAssigned = false;
private void Awake()
{
Debug.Log(isGameManagerAssigned);
}
``` Outputs true in build, false in editor.
So its not that itโs changing by itself, itโs that itโs not getting changed? Your original question was a bit confusing in that regard.
If this is the only place its references how would it ever be set to true?
That's what I'm wondering.
Hey guys, I'm trying to retrieve the number of ContactPoints2D of a BoxCollider2D with the GetContacts() method, but I don't see any way of accessing the boxcollider's contacts array, could anyone help me with that?
That method literally returns an array of contacts wym?
Hey, does somebody know to do to such a hower effect in c# script?
so I just to have a new contactpoint2d array as a parameter of the method?
No, that method returns an array of contact points
huh
it is done with the attribute [tooltip]
thanks
If thereโs contact points thereโs a collision. If thereโs a collision it calls the collision methods such as OnCollisionEnter2D, which takes a collision2D parameter (or something similar), which you could then do collision.contacts to get an array of contact points.
But it's just gonna be the amount of contact points for that single collision, I'm trying to get the number of all collisions
If I'm understanding correctly
Why not just process them as they occur? If youโre just getting the number count it yourself, + on enter - on exit
@zealous tundra thereโs also Collider2D.GetContacts()
ok
๐ญ
Does anyone have any experience with setting up skills for RPGs?
In my game, players are able to choose which skill goes on what slot, so I can't just hard-code it into a button.
I'm having a hard time wrapping my head around the idea when it comes to custom effects. Like, one skill could be an attack, buff, debuff or passive. Or it could be something like a Movement speed buff / teleport
Any ideas or input would be appreciated because I'm genuinely just stumped atm
Are you asking what skills you should make?
No. Moreso how to handle them. I already have a list of skills that the player can have
What do you mean handle them?
At first, I was going to go with ScriptableObjects but they don't have access to Couroutines, which I was going to use to handle cooldown / duration
I still dont know what you mean to โhandle themโ.
I have a single player collider that I want to keep track of its current colliding sides, like up, down, left and right. I want to know when exactly the collider's side starts and stops colliding, to for example know when the player can wall jump. So it's not only about the number, it's about which side does the collision come from. I already have a method that does the second part, but I want to have a method that updates bools of which sides of the player are colliding with stuff whenever the player enters or exits the collision.
hay how do i accept a prefab in a script?
only a monobehaviour can Start a coroutine, but SOโs can have IEnumerators that your player Monobehaviour can call off of them
public GameObject
Ah as a GameObject, thanks
What shape is the players collider? Square?
yup, there will always be 2 contactpoints per collision
i think
lol
Just have 4 sub-objects with edge colliders as arrange them into a square, then you can do the contacts method to count the contacts for each side
I tried that at the very beginning, but it made the colliders register 2 collisions whenever an collision occured near the corner of the shape
even with continuous collision detection
Then just have one collider and check the collision is to the right/up/down/left
That's what I currently have
But the thing is
When that collider exits a certain collision I don't have access to the collision points of it
so I can't determine what from what side is it exiting a collision
OnCollisionExit2D doesnโt work?
nope
Like... how would I be able to keep skills unique but also have them accessible for a slot system?
Let's say I have the following skills:
โข A dash skill
โข An attack skill
โข A Debuff skill
I'm looking for a way to add each skill into any slot that the player chooses (which they can change), and have it function properly.
For example, if I pressed the Dash skill, it would make the player dash forward etc. It would be easy to handle this if I hard coded the logic and stuff into a slot itself, but since I'm making the positions of the skills in the slot customizable, I need to go with a different approach
Probably a shit way of explaining it, so sorry in advance lol
why?
I mean, the method does work but I can't access the contactpoints of an already exited collision
I'm preety sure I tried that
decouple the slots from the skills
the slots should barely matter, really
you just have a list of equipped skills (and maybe corresponding keybinds)
I would create an abstract Skill class and extend that class instead of monobehavior on other skill classes, then I can accept the Skill class in any of the slots.
Iโd have an abstract DoSkill method or smth in the Skill class that child classes have to implement.
Then when slots are pressed just call the DoSkill method on the abstract Skill class assigned to that slot
I highly recommend checking out this video. Especially if you want to use SOโs for your ability system. https://youtu.be/ry4I6QyPw4E,
This video shows you how to make a simple Ability System for all kinds of games in Unity. The system can be expanded easily and it allows you to change abilities in run time.
Yea you can. It takes a collision2D parameter Iโm pretty sure, which would have a list of contact points that left.
General idea is that your player doesnโt know how to perform the ability, your skill should handle that
I'm pretty sure I already tried that, but I'm gonna try one more time just in case, thanks
you'll probably need to express some high-level ideas in the Skill class
I wrote a system up for an RTS game (well, more of a moba, I guess: lots of active skills)
the abstract skill class tells you things like "this is a unit-targeted ability" and "this ability needs to channel"
but all of the actual behavior is contained in the specific implementations
ah true
The only thing my abilities have is usually a reference to the source player for some calculations such as killing blow ect
yup, it's trying to access contact points that are simply not there
I would say it doesnt even do that
Ah, something like that might work out. I'll give that a try
Unit-target and channeling are skill-specific, or at least make another abstract class that extends skill
Tyty, appreciate it. I'll give it a look
changed it slightly ๐
i wanted to avoid the diamond problem
consider: an ability that can ground-targeted OR unit-targeted
or even self-targeted, by double-tapping it
I fixed that problem by making everything I do AOE
How would that EVER arise in c#?
...if you wanted to inherit from two things?
You canโt inherit from 2 classes
it's a problem in any inheritance-based system
i guess it's not the diamond inheritance problem if it's impossible from the start
Yeah, there's a lot of cases where you have to throw on some interfaces to untangle some of the logic
Even then not really in this pretty basic implementation of inheritance
i made ability targeting happen outside of the ability itself
the targeting system asks the ability if what i'm pointing at is a valid target
Thatโs bizarre it would do that. I think its time to do it a different way then.
(and ask about both the ground and the unit i might be hovering on)
if nothing is valid, you get a big angry red cursor
Is it possible that my way of accessing the contact points is doing this
lol
I got rid of direct targeting since it started to create more complexity on a dynamic spell system I wanted to make
Why are you doing -1 and -2?
to uh
I found that targeting an area or point direction is the idea way to really meld stuff together
Just do other.contacts from the start??
get the first contact points of the array lol
Do contacts[0]
contacts[1]
yeah, and the GetContact method gets a specific contact point form that array
I think
just other.contacts[]?
you're subtracting an integer from an array...
(you should set up your code editor so it highlights errors, your syntax was invalid)
no, access an index of it. Contact[0] would be the first item in that array
No theyโre not lol
oh!
right
you give it an array, and it returns the number of contacts stored in the array
It lterally works
there is no error
It works? Whereโs the invalid syntax
Yeah it works, I saw GetContact() (singular)
anyway, it sounds like there are just zero contacts here
Which by the way is super bizarre
LMAO
nah, it's decently common
it's a non-allocating way to get a variable number of results
it works the same way ๐ญ
the int that gets returned lets you know how many slots in your array were actually used
.length is fine
oh, I think I see what was going on here
you passed other.contacts to other.GetContacts
Thats not whats happening man
if that array was empty (it probably gets lazily initialized to avoid allocating memory when not needed), then it would see that you gave it an array with zero elements in it
and thus put zero elements in the array
and return zero
you're supposed to pass your own pre-allocated array to GetContacts
I referenced the array, then got a singular contact point from that array
No youโre not!!!
Wtf are you even talking about!?
this is exactly how it works
this is a very common pattern
Wait is this to get the contact count? Collision2D has a contactCount property
You need to specify youโre talking about Collision2D.GetContacts!
...that's what we're talking about, yes
Hello, I have this code to click on a specific GameObject collider and show its UI to upgrade it, but when an enemy approaches its colliders this code stops working, there is some order of priority that is preventing the raycast from reaching to the collider that I want
Idk man, this conversation has been going on for so much longer than youโve been here we were talking ab other stuff. Thereโs another .GetContacts that does smth else
true
we are talking about this
I still don't know how to get the number of collisions of that collider
it started off here
this is what you want if you're looking for the number of contact points for this specific collision
simplest way is to define an int counter, and inside OnCollisionEnter just do counter++
Ahhh so its contact points, that is different
that wont work if yaโll would read what theyโre trying to do lol
Heroshrine already told me to try that but it doesn't work in my case
this would count the number of collision events, not the number of contact points for a specific collision
.
Srry, I have not read about was going on lol
.
Yo why does my console warn me that says "Failed to fetch saved variables from player prefs:" and I can't see how to fix it
So the collision exitโs contact points array is 0 width?
Get the direction between the collider center and the first contact point, then dot products or angle to find the side?
exactly
Already tried that
that's what I would do
They need to count the collision points that exit but onexit apparently returns 0 collision points
So I have the following problem: I'm using a rigidbody for my character. It has a physics material of friction 0 and bounce 0 (uses min value for both). Friction is 0 because I'm calculating and applying friction manually when the character is grounded.
When my character lands on a slope from a long fall, it slides a little before it stops.
Any ideas on how to prevent it from sliding on landing? I tried canceling velocity on OnCollisionEnter and also on FixedUpdate but nothing seems to work. I'd rather avoid Update because I want to keep the movement as frame-independent as possible.
I tried that at the very beginning, but it made the colliders register 2 collisions whenever a collision occured near the corner of the shape
They said they get double registered collisions on the corners which they donโt want ๐คท๐ปโโ๏ธ
I wasn't there at that time, lol
put them on separate child objects, so that you can handle the events separately
you'll still want to hear about both collision events
And don't make them overlap
overlapping shouldn't really matter here
you can still have a big collider come flying in and hit two of them at once
But I don't want that
Iโll let you guys go through it then. I tried everything i could think of without saying to do it a different way.
if I walk into a corner, surely I'm both colliding from below and from the left side
If a bullet hits from the left side and the player gets his left side and head hit that wouldn't be nice to experience
well, then don't make the head hitbox gigantic
it's a 2d game btw
i'm just saying that it's reasoanble for the "left" and "top" colliders to have some kind of overlap
you can, of course, design them however you'd like
how is that reasonable?
it depends on your game
I don't really get it
i'm not sure why there's a huge hangup about it, though
Additional note on this: even with a high friction value on the physics material it still seems to slide
I don't want a single bullet to deal damage to two parts of the body
just make the colliders nice and distinct if that's an issue
I already tried doing that
you can also do some logic to avoid duplicate collisions
let me explain
if the same collider hits twice, ignore the second hit
wait, you just want to know or add to a counter when collision from a side occurs and remove it when the (collided) object exits? how are you checking for the collision from each side? individual GameObjects with a Spherecast/XXXCast, or a single collider by checking the direction of the collided object to the main object?
again, this is a question of game logic
gameObject being the player
cool, using gameObject here is unnecessary though . . .
oh right
comparing the contact points seems kind of weird
i guess it works if everything's an unrotated rect collider
I'm checking how are those aligned this way
yeah
can you describe the higher-level gameplay logic you want here?
not the specific implementation
that will help me understand what the best option is
.
that is the implementation. I'm asking about the gameplay.
Do you mean how do I want to use those collision bools?
Right.
You may be experiencing the XY Problem -- getting stuck on one specific solution when the original problem has a better way of being solved
To check whether the player is colliding ONLY with a wall (collision only from left ot right side), to check whether a player is still in collision with a laser (that's taking hp constantly when collided with)
and it might be very useful later on
So if you're getting lasered, then you shouldn't be allowed to do a walljump, or whatever
those are two different examples I gave you
hi , im looking for a way to draw a circle in a shader and I came across this function yesterday
does this line of code really draws a circle ? , how / or how to even test it ?
i copied it in my (to do list) but i forgot to keep the reference link so i dont know how it works really , but it's just 1 line of code.
float DrawCircle(float2 pos, float radius){return length(pos) - radius;}
so, for the laser thing, you don't care about direction at all
actually, let's make a thread for this
collision
one is checking whether in a single moment the player is colliding with only with a wall
this line of code doesn't draw anything. Just a little math. Seems to just be subtracting a number from the magnitude of 2D vector
this would be much easier if you used separate colliders to detect a collision from each side. then you can tell which side has a collision . . .
Question:
How this code can produce the following exception?
MissingReferenceException: The variable renderers of TimeRoot doesn't exist anymore.
You probably need to reassign the renderers variable of the 'TimeRoot' script in the inspector.
It doesn't make sense, I'm already checking for null in the line above.
drawing things in shaders doesn't really work like the way you're thinking. There wouldn't be a function like "DrawACircle()" that imperatively draws a circle.
Shaders are programs that run on a per-pixel or per-vertex basis. So for example a fragment shader is a program that runs on a single pixel and determines what color that pixel is. So I would expect a fragment shader that draws a circle to do something like, conceptually:
"Is this pixel within the circle? If so, make this pixel red. If not, make this pixel transparent".
the end result when that is run on every pixel in an area is you get a circle drawn on screen.
renderers, not renderer
is it renderers or renderer? the message you posted is spelled differently than the code you provided . . .
although, I do not see a variable named "renderers" in this screenshot, indeed
Then the exception it's giving me the wrong line
that explains a lot , thanks
but what does length(float) (aka: length(pos)) really do ? i cant google it
And yet, renderers is an array, arrays can't be "Missing", it is null or not, and didn't get a NullReferenceException when I created the span
well, the compiler doesn't lie
make sure your code saved, make sure it compiled in unity, and give it another go
it's just telling you the length aka magnitude of the vector
it's just like Vector2.magnitude in C#
note that pos is a float2, not a float which is the same as Vector2
So I'm not understanding what is going on then
make sure that you are getting no errors in unity. clear the console, run the game, and trigger the bug again
yes, thanks a lot , that is probably more info that i expected to get from that 1 line , thank you so much โค๏ธ โค๏ธ
Anyone knows what's can be wrong?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hey guys, I need to apply a fix to this, it was my bad that I wrote it poorly, but have to deploy a fix fast:
long lastDateLong;
DateTime lastDate = DateTimeOffset.FromUnixTimeSeconds(thisDateLong).DateTime;
bool within24hours = (DateTime.Now - lastDate) <= TimeSpan.FromHours(24);
if (within24hours) {
// do something
}
This code checks if lastDate was 24 hours ago from right now, but what if it needs to check is if lastDate was yesterday vs today
So like if it's past 12am from the lastDate's day
Anyone know how to do that?
Maybe this
https://www.youtube.com/watch?v=Z6pEAngpR9I
๐ How to work with date and time. In this tutorial we'll focus on the system date. How to get it, and how to format it.
๐ Extra tip: You can get the NAME of the day by typing "ddd" or "dddd". Try this:
print("Today is " + System.DateTime.UtcNow.ToLocalTime().ToString("dddd"));
ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท...
Does anyone know how the coordinates are set up for Texture2D.GetPixels()? If I wanted to start at the top left pixel is that (0, 0) or (0, texture height)?
Ah I see, so you can even do DateTime.AddDays(-1) and check that way
testing to see if it works with 24 hours versus a local timezone's actual day
DateTime.Today gives today's date at midnight. Compare that to your date
Damn this is the instant easiest way to do it
Wow
DateTime.WhenIWillDoTheThing -> always returns tomorrow
Watch out, only if DateTime.Procrastinate is true. Fortunately, that's a const bool and is always true
DateTime.WhenWillIDoTheThing = DateTime.WhenItsDue.AddDays(-1);
๐จ
are you sure you're looking at the right instance of this component?
there could be another object in the scene with it attached
seems you have more than one in the scene . . .
which object highlighted when you clicked on the log from the console?
Not sure in what that affects? The log true true is produced in the exception, it says it's not null... despite the exception being missing
Can you post the full error message? It usually comes with a stack trace that points to the exact line that threw the exception
0, 0 is bottom left
So the latter (0, height) would be top left
To convert XY coordinates into an index in the color array, you can use y * width + x
MissingReferenceException: The variable renderers of TimeRoot doesn't exist anymore.
You probably need to reassign the renderers variable of the 'TimeRoot' script in the inspector.
WhiteboardGames.TempusVitae.TimeSystems.TimeRoot.ChangeElements (System.Boolean enable) (at Assets/Scripts/Time/TimeRoot.cs:192)
WhiteboardGames.TempusVitae.TimeSystems.TimeRootManager.InitializeRoots () (at Assets/Scripts/Time/TimeRootManager.cs:51)
WhiteboardGames.TempusVitae.TimeSystems.TimeRootManager.Start () (at Assets/Scripts/Time/TimeRootManager.cs:38)
ah ok, I see. Thank you!
is the array ordered from bottom left to top right?
class TimeRoot, line 192. Is that what you highlighted here?
It highlighted a gameobject in the DontDestroyOnLoad section. The component is a different one which produced the error does exists and is not destroyed.
nvm didn't see this, thanks!
Yes, row by row
The line in red in the picture I put bool enabled = renderer.enabled;.
ok cool
Can you show how you're populating that renderersSpan collection?
Span<Renderer> renderersSpan = renderers.AsSpan(0, renderersCount);
And renderers is: [SerializeField, HideInInspector] private Renderer[] renderers;
Okay so you serialize it, but hide it in the Inspector
Something isn't adding up here
"renderers" vs "renderer"?
I fill the array using ISerializationCallbackReceiver.OnBeforeSerialize()
It's complaining about your array yes
Yeah, super odd
The line is renderer, but the error is renderers
Can you change the name of the array to something else?
Any chance you haven't saved your code recently or there are compile errors?
are there other compiler errors?
Code is saved, compiled a few seconds ago
No compile errors
So is there a variable called renderers at all?
It's a field
is it possible to listen to a event without the class being instantiated?
Only if it's a static event
Are you doing async stuff perhaps?
Async loading an scene, the error happens when I change from one scene to another... but only 15% of times
Hmm... That might be a clue
Once you changed the array's name, try to get the exception and see if it's complaining about the array
Can you take HideInInspector off for a minute
you might just have a reference to a destroyed object in there
Didn't help:
MissingReferenceException: The variable renderersArray of TimeRoot doesn't exist anymore.
You probably need to reassign the renderersArray variable of the 'TimeRoot' script in the inspector.
and you can't see it because it's hidden
Ok
So yeah it's definitely complaining about your array
Even if you access it "though" the span
Actually it's even weirder since it's an array
you'd expect the array itself to be fine - at worst only containing references to missing objects
I'm pretty sure it's the mix of the two attributes here that makes the weirdness happen
where could I subscribe to the event tho? OnEnable can't be because the class isn't instantiated so
the attributes say, "i want to see you, but i don't want to look at you," lol . . .
It's more like "I want to serialize you but not see you".
Your question is unclear. Did you mean the class that owns the event is not instantiated, or the class that listens to the event
the class that listens to the event
When do you want it to subscribe then?
and what code do you want it to run?
the event itself need not be static in that case but you'd need to get a reference to the particular instance on which you'd like to liseten for an event to if it's not static
basically - can you back up and explain what you're trying to do?
Clicking the first message doesn't highlight anything. But the second one doesn't have the same element at the specified location, this obviously happens because I'm compacting the array during the iteration by filtering out nulls.
The weird thing, is that if I remove that cleaning, the error is not happening... or at least not in my current tests, it's difficult to know if it actually got fixed since it only happens 15% of times.
wait, you're altering the array while iterating it?
Oh, just happened again...
Yes, hence I have two indexes i and j
i'm using a singleton pattern that instantiates itself when it's called in the scene for the first time
so if I for example call UIManager.Instance.OpenDeathUI() when the player dies it works fine
tho I wanted to subscribe to the OpenDeathUI to the "onPlayerDeath" event and triggered it when the player dies instead of calling the UIManager on the player.
just wondering if that's possible
So sounds like both classes are getting instantiated
that's a no-no (unless you're iterating in reverse which it looks like you're not) . . .
Still different values
that causes all kinds of issues . . .
I'm basically doing:
int j;
for (int i = 0; i < length; i++)
if (filter(span[i])
span[j++] = span[i];
That is safe.
but the UIManager is not instantiated until the first time that I call it and I can't subscribe the event on the UIManager because OnEnable is only called when the object is set to active.
You'd basically have to have either:
- The player call a function on UIManager to register itself with the ui manager where you can then subscribe to the event ont he player
- Have whichever script that spawns the player pass a reference to the player to the UI manager
- Make onPlayerDeath a static event and then you can just directly listen to the event from UI Manager in Awake or OnEnable for example
because OnEnable is only called when the object is set to active.
I don't see that as a problem. We don't care about the event until it's active anyway right?
I disabled the mutating and yet it happens
try removing the Span altogether . . .
Ok
Not sure if this is the right place to ask, but has anybody tried setting up git with fmod plugin?
Should you gitignore plugin folder? Or will it break the integration and it's ok to store the plugin in the repo?
have you shared the entire script yet?
So this function is suppose to focus the camera on an object, and it works great but only with Pitch above 0, as soon as it gets below that it snaps back to the top, and it repeats. The normal look around works without any issue, and can go below 0, Please help
public void FocusOnObject()
{
LockCameraPosition = true;
if (focusObject != null)
{
CinemachineCameraTarget.transform.position = transform.position + camFocusPrePos;
Vector3 targetDirection = (focusObject.position - CinemachineCameraTarget.transform.position).normalized;
float singleStep = 5 * Time.deltaTime;
Vector3 newDirection = Vector3.Slerp(CinemachineCameraTarget.transform.forward, targetDirection, singleStep);
cinemachineTargetPitch = Quaternion.LookRotation(newDirection).eulerAngles.x;
cinemachineTargetYaw = Quaternion.LookRotation(newDirection).eulerAngles.y;
}
}
it's a mistake to use euler angles like this
for exactly the erason you're saying
you can kinda "hack" it by combining your code with https://docs.unity3d.com/ScriptReference/Mathf.DeltaAngle.html
okay
Or you can use Vector3.SignedAngle
How would you hack them together?
Removing the span and the array mutation didn't help ๐ฆ
so replace the cinemachineTargetPitch = Quaternion.LookRotation(newDirection).eulerAngles.x; with Mathf.DeltaAngle(CinemachineCameraTarget.transform.rotation.eulerAngles.x, newDirection.x);?
can you share the whole thing?
Pastebin
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.
and what's the stack trace for this current script?
For that I would need a moment to reproduce the bug with this script, but I would say it's the line enabledRenderersSpan[j] = renderer.enabled; (170).
so I have this script that generates an island and places villages, caves and fountains on them, how would I get rivers set up?
code: https://hastebin.com/share/uxixoceneq.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
went if the first one, thanks !
I don't know where to ask this question.. How would you go about rendering a crowd made of thousands of 3d people? (like in FIFA games) They should also be animated
Your best options are:
- Compute shaders
- vertex shader animations
- ECS
Even though at least for now they are 3D stickman.. so for the animation there doesn't need to be the skinned mesh renderer, but more like rotating the capsules that represents the arm, the leg...
also a full stickman object is probably overkill
Ok thanks!
!collab
๐ข Collaborating and Job Posting
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
wdym?
!collab
๐ข Collaborating and Job Posting
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
if you're using full GameObjects for these things you will have issues
way too much memory usage
I am using Unity DOTS for my game but I think even with DOTS it would be way too much
I have 2 colliders on my object. One circle2d and one box2d. I want to check if a box2d collider hit another box2d collider. How can I do that?
OnCollisionEnter2D
check the collider type of the collided object . . .
Forgot to mention, the circle one is bigger than the box one and if i use OnCollisionEnter it will register the circle one
Collision2D contains the https://docs.unity3d.com/ScriptReference/Collision2D-otherCollider.html property - which ironically actually checks which of your own colliders was involved
they (colliders) should be on separate GameObjects . . .
if the circle is bigger then the box won't be colliding with anything anyway