#archived-code-general
1 messages ยท Page 369 of 1
What is it you're looking for? Do you want them to constantly move the same direction? Or do you want something to 'push' them away?
what i really want is to click a point on screen and then the particles will recieve a force wherver they are pushing them to the point of click
Take a look at this post, it might be helpful: https://stackoverflow.com/questions/66468212/unityis-there-a-way-to-set-the-position-of-every-particle-in-a-particle-system
You might also want to consider whether or not using particles is the right choice here, depending on how much you will want to manipulate them
This worked well enough and i dont have to make two silly scripts for one functionality xD is nice
Is there a "clean" way if there's water everywhere at the bottom of my map to have an infinitely large respawn trigger at the bottom (where there water is), or should I just make a very large trigger and place it there?
presuming this is 3d, why not just check for a specific z coordinate
A very large box collider is easy enough
The safest way is to implement an if check in your character controller that respawns if transform.position.y is lower than some constant.
I would also go with a trigger.
Y position can change if you have different heights terrain.
eg you can also slope a trigger angled, you can't slope positions easily. Ofc depends on your level/use case Y pos check should be sufficient
You can make a component on each level that contains a float for kill height then.
Yeah I mean that works but Imo a trigger is also easier to see clearly visually in the scene
there is no second guessing on numbers etc
Also, the preference depends if you want this for an emergency catch all respawn for when a character falls through the world or if it's for intended obstacles with death pits etc that player might fall into during regular play.
if its flat, number should be easy, if you have many variations in height, triggers are better
You can draw a custom plane gizmo from the component's OnDrawGizmos ๐
I know but now thats already more work than a trigger ๐
Well, better be safe than sorry when it comes to falling through the world due to a hole in colliders somewhere 
its not like the cartoons? if you fall into a hole you just end up on the otherside of the planet 
A component on each object that checks your position, which may need to change between scenes, is a lot more setup than a large trigger
Not really, you only need to add like 2 lines to your player controller to check the current height and call respawn from there instead of checking if you collided with a respawn trigger from OnTriggerEnter.
i didnt understood that.
And the part about "which may need to change between scenes"? Suddenly more bad hardcode. And again you have to attach this to anything that can respawn
does anyone know what usecase this Attribute has?
https://docs.unity3d.com/ScriptReference/DelayedAttribute.html
I can't think of any...
A simple component that contains just a public float KillFloorHeight. Ain't exactly computer science.
It's not "bad hardcoding" to want a plane that's always infinite as a catchall. What if something clips into the ground and gets yeeted far beyond the bounds of your trigger volume.
If you choose to ignore everything I said about why it's not as simple as trigger, then sure.
I normally dont consider whataboutisms. If the player gets launched that far anyways you have larger issues
What if my players character gets launched into the sky so far it takes an hour to fall?
i think its used on variable types interesting attribute nova never used that before.
well yeah it says it right there which types its for lol
float, int, or text field
I was just curious if someone had a practical usecase for it
It does look pretty niche, maybe more for editor stuff? Since I only see this post
https://discussions.unity.com/t/how-to-do-a-editorguilayout-propertyfield-delayed/796751
yeah seems so ๐
It's probably for use cases where you don't want the values to be immediately updated while you are still typing, eg when value changes it triggers some side effects that are undesirable to trigger on every key stroke.
That does make the most sense, though even knowing about that attribute I'd probably implement that functionality myself
yea kinda super niche surprised its there lol
I have a script that returns a Mesh based on (int sides). I'm repeatedly getting the same Mesh from the same sides. Should I just add a dictionary[int, Mesh] and not generate the same Mesh over and over, or would storing them be less convenient?
It would probably be beneficial to cache and reuse the meshes, but it also depends how they're being used, what their lifespan is, how many times each mesh is being reused, and if the users of the meshes are modifying them in any way.
You will also need to manage cleaning up the cached meshes somehow
Just GetComponent<MeshFilter>().mesh = _mesh;
Nothing else
Each mesh would be reused probably like 20 times
I would recommend using .sharedMesh if you don't intend to modify the mesh.
Whats the difference?
Technically I believe when setting the mesh there is actually no difference. But when reading the mesh, if you use .mesh it will allocate and create a brand new mesh unique to this one object, with the expectation you plan to modify the mesh and don't want to affect other objects. .sharedMesh allows you to get the original mesh without creating a copy, with the understanding that other objects may be sharing the mesh so changing it may affect many objects.
ty
I have no idea how to change my tilemap back to rectangular, I accidentally made a hexagonal one after and it changed all the others, I cant change it back with undoing (crtl Z) it...
so now its all jumbled...
Click on the Grid
change the cell layout to whatever you want
nevermind I fixed it, but I apreciate the help! turns out I was lucky enough that I used crtl + s right before the issue occurred!
i would set up VC for your project so you dont lose anything if such were to occur
whats a vc? is it like a backup?
oh right, ive heard it before, ill take a look, I appreciate it
How come this setting works perfectly in editor but has no effect in WebGL?
Application.targetFrameRate = -1;
Ah, so there's no way to bypass that?
I would assume not, if it's "always limited by ___"
Yeah.. too bad, good to know though, thanks for the link to the doc
I created a class deriving from EventTrigger for some event overrides, but now I can't see any variables in that class in the inspector - is there a way to deal with this?
should I access OnPointerEnter etc. in a different way?
There's no need to derive from EventTrigger
You can and should implement the interfaces yourself
IPointerEnterHandler for example
oh yea, that works! thanks!
So I'm trying to compare two colors by thinking each of the r,g,b values as x,y,z and comparing their distance in the 3d world space. The algorithm does generally good, but sometimes two distinct color's distance could be as small as green and light green. What extra check could I add to fix this?
These two for example
Are you trying to make it more sensitive or less sensitive?
i.e. you want those to be the same?
Neither
One thing you could do is convert your RGB color to HSV: https://docs.unity3d.com/ScriptReference/Color.RGBToHSV.html
And then just compare the distance between the hues (with Mathf.Abs(h1 - h2))
or do some more complex analysis on the whole HSV set
it detects these types of cases
like "if it's within n hue value but also within m brightness" for example
but then mathematically these are near each other
I'll look at that thanks
So you want.. what? I'm still not clear on that
an extra check like this
I'm not an expert on colors but i got the impression that colors could look very different to the human eye and be close to each other in terms of rgb 3d space
and the other way around, they could look pretty same and be distant from each other
so what I wanted was an extra check besides the original equation
well certain things like greens all look more imilar to each other than on the other end of the spectrum
just due to the way eyes work
I believe I helped someone solve this a long time ago but one thing you can do is adjust the sensitivity of your distance check based on how far the hue is from green
i.e. with a remap function
that makes sense
{
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
var emitParams = new ParticleSystem.EmitParams();
emitParams.position = mousePos;
cosmicDustTap.Emit(emitParams, 1);
}```
for some reason this is making the emit position very high up on the y axis
and not on the mouse psotion as it shod be
if you are using a perspective camera then mousePos is just going to be the camera's position https://unity.huh.how/screentoworldpoint
its orthographic
then it's going to be at the same Z position as the camera, so either way it's going to be too close to the camera so the camera won't be able to render it
i dont think it would it shod just give the position of the mouse in world space
cause thats how it workedbefore
you can think that isn't how it works all you want, but that is how it works
if no Z position is specified then it will be the camera's Z position. and naturally that is too close to the camera for it to render
well i can see the particles so they z position is fine
I'm trying to use a lambda function to get the objects with the lowest rect.x, not the lowest rect.x float value. This is my attempt so far Room room = level.rooms.Min(r => r.rect.x); but its only giving a float
its just the y position thats off
and have you considered that perhaps the particles you are seeing are the ones that have moved up and away from the starting position of the mouse's X and Y coordinates and the camera's Z coordinate?
no cause im only spawning 1 in and i can see it appear in the wrong place
Room room = level.rooms.MinBy(r => r.rect.x);```
Argh so close. So Min will give the value but MinBy gives the object?
thanks!
MinBy is not available in unity, it was introduced in .net 6
but I feel so big brained when I use Lambdas
could also just grab the source from source.dot.net or something and drop it into the project (with some modifications to make it compile)
you'll get over it
you can still use lambdas
and write your own MinBy function
Do you think normalizing rgb and hsv differences to be between 0-1 to have a single tolerance float and not seperate for both would make sense
I don't think a single tolerance float would necessarily make sense, no - and that has nothing to do with normilzation (they're already between 0 and 1 as it is)
the rgb value can be sqrt(3)
im trying to get navmesh to work in 2D. Im using a git repo that i found to try to get it working, but it throws the "too far from navmesh" warning 9/10 times it tries to spawn and move an agent
and for hsv, s and v are between 0 and 1 but h sometimes isn't
does anyone know how i can fix this? im wondering if the agent is just passing through the navmesh or something
they do have the same z coord
yes NavMeshPlus is what you want
thats what im using but its not working for some reason, ive done the setup like 3 times, not sure what im missing
you would have to show some details of your setup / what you tried.
I ended up having seperate tolerance floats for each one, I've created a script so I can fine tune the tolerance values until they fully meet my expectations. Ty for all ur help
looks like something else is breaking this rn, ty anyways
Anybody know why
item.hideFlags = HideFlags.DontSaveInBuild;```doesn't work for the "StreamingAssets" folder or an mp4 file inside it and if there is an alternative to not include that folder in a specific build?
StreamingAssets assets are not included in the build as assets. Instead the files are simply copied over verbatim
There's no way not to include StreamingAssets in the build because the whole point of StreamingAssets is to include it in the build as verbatim copied files
Why do you want or need this exactly?
if you dont want those files in your build then delete those files.
Hello, I've been working on a problem for most of the day and its got me stumped. I have an NPC that is supposed to complete jobs by moving around the navmesh to given locations and carry out a task at each given location.
In my current setup, I have it moving to the location to pick up an item, then move somewhere else to discard it. The moving part works great, the picking up and discarding not so much.
the NPC brain script has a public array containing all of its tasks. The tasks right now are empty game objects placed around the map. It works for pathing. This is where I am struggling. In my design the tasks contain the associated action inside them, so the pickup location has a script attached which has a method to give an item to the NPC. The NPC has a reference to that script through its parent gameobject (the task object), and the NPC calls the method to give itself the item from the task
Now that I'm writing it out, this seems rather backwards, but I was hoping someone had a better idea of how I could do this.
I was playing with putting a collider at the task location to trigger the task, however I'm building for a warehouse environment where lots of NPCs doing the same jobs may pass through the collider as they are moving around
I have an actions system in a project I'm working on.
The actions are just a list of so's that the character(or a character template) has. I then use goap similar system to generate an actions plan. That part is probably irrelevant to you, but when I create an action within the plan, I provide it all the required info, like the item reference that it needs to pick or an object it needs to interact with, for example. These references are passed to the system from the character sensors. The sensors update every frame(or a few frames) and detect all kinds of objects within some radius around the character. If the detected item is an item container(a physical representation of the item or an inventory in the game world), I add all the items inside to a list of detected items.
If I'm understanding that right, I should essentially be making the equivalent of a pickup button for the AI? Then I just have it be able to see and decide which one to pick up based on what's around it?
more specifically, it would be like "your job it to pick up chicken" so it moves to the chicken point and looks for "chicken" in the list of detected items?
Depends on how you want it to work. That sentence of yours includes many different separate systems/mechanics.
Yes.
But again you're mixing up 2 separate systems:
Action decision and action execution.
The latter one should work the same way both for ai and player characters.
The former one is what replaces the player brain for the npc.
Action decision is going to be handled by an outside source, in this case preprogrammed but in the final form it will also be able to be assigned at runtime
In my project, both the player character and npcs use exactly the same system for action execution.
just executed from a different source (human input vs... NPC whatever) right?
Yes
ok yeah. I essentially have the same. Everything is using the same inventory system, I just need to make the NPC perform the action. Neat
You probably don't want the UI to be a part of the this actions/jobs system at all. It should be part of the player controls.
In this case its exclusively NPCs, so that takes care of itself
Well that makes a lot more sense now. Originally it was "Go to chicken and activate the chicken action and do what it tells you", whereas now it will be "Go pick up chicken"
I just need to figure out how to attach the action to the location
Because right now we have "go chicken, go truck"
In my case, the action definitions are scriptable objects, so I can just assign them to an interactable object if it needs a specific action.
Or do it via code.
scriptable objects sounds like a good approach. I will need to go back and study them again because I am not very familiar with them
reading into scriptable objects more, I dont know if I'm misunderstanding but they cant store implementation? only data?
I'm not entirely sure where to look or how to properly word this: I have a scriptable object in it a few serialized classes attached, these are just a lists of the same scriptable object.
I made it so I could just right click and make the object, the idea is that the scriptable object has 4 lists which just say what can be near its 4 sides.
Is it possible when I had an object to the list, it adds the second object to the first objects list?
Essentially the lists look like this, in editor I drag and drop in other nodes. I'm wondering if its possible that when I add the prefab node to this one, it adds itself to the other
Hello so i recently set up DevOps for my project and have it sending discord webhooks. Is there anyone that is familiar with DevOps and know if their is a way to change it from using your email in the webhook message to your username?
Sounds like you need some kind of extra database/serialized object manager, that handles all connections. If I understand you correctly, lets say you add a node to the top list of object A, it should add the object A to the nodes bottom list?
๐ Large Code Blocks
Use 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 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.
The objects all have 4 lists for directions, the idea is valid connections, if I add object A to object B's top list, it should add object B to A's bottom list
I think we're on the same page
Hey guys, im using ARM IK of Final IK to do True First Person Shooter(Full Body), but im struggling in the hands position in realtion of the camera with the rotation of spines. When the spines are not rotated(changed the position because of the other spines rotation) its works more than fine, but when rotate for a reason i dont know the hand are considering the spines rotation, but i get the hands position before the spine rotation. In my head its supposed not consider.
Ill be very glad if anyone could help me in this, im struggling on this and other logics of this script has months.
The Code:
https://gdl.space/dexifedexa.cs
The Examples:
No rotation(the hands position are same of the second examples that is no spines rotation)
Building a WebGL game for multiple websites each having their own intro video. I only want to include one video per build instead of all the videos. I figure something else out.
when the white object (player) goes through this black doorstep, it begins flying up
Movement is only stored here
any ideas?
do not cross post
Hello, I am trying to publish my first mobile game and am very close the last step really is just building it to an abb file but when it I try to build it, at the end, it always does this.
not a code question #๐ฑโmobile
ok
Then I guess you have to make your own node check manager, that will update all nodes depending on their inputs and outputs
Hey i want to save (override) a prefab variable from the copy that was initialized. how is this possible?
They can, but you should avoid it is possible.
Saving and overriding are completely unrelated so it's not quite clear what you want, but if you want to change a variable x of an instantiated (not initialized) copy to y then
var copy = Instantiate(prefab);
copy.x = y;
i instantiate a prefab and during play i save a score. But i need that new score on the original prefab, because the instantiate is just a copy and the score is lost upon destroy ofc
Why do you destroy the object that stores the score
Then don't store the score in the level
but its the best place for it. so is there a way to save a value back to the original prefab
How is it the best place for it if it doesn't work the way you want?
If you only need it in the editor, you can save it via some editor API.
i need a reference on all the highscores to save it in my json
What reference?
Json doesn't save references.
Any pointers?
Hey, is there a built in/simple way to change anchor + pivot through script?
So TopLeft would be stuck to the corner at correct pivot(object would not go outside of parent object at 0, 0 position)
or do I have to if/else 9 times for each anchor
Hey, is there any way to detect if mouse is over line renderer?
any tips on how to prevent this? Creating a jenga game and the blocks seem to be clipping
https://media.discordapp.net/attachments/497874196274348032/1283390509292716134/image.png?ex=66e2d20d&is=66e1808d&hm=9bf7865b74bbae1219c76dba7809f97430e2ca24a5d92756db6e2eaaf5953610&=&format=webp&quality=lossless
i was coding and suddenly i cant do any like unity shortcuts or something
like i cant write transform, gameObject, or anything like those shortcuts
not sure what happend
don't crosspost
mb got a fix anyway
It's really not clear what we're looking at.
fixed it, blocks were clipping through eachother
I'm back on my NPCs and a little lost again
This is the flow I've settled on
My issue is specifically the end of the flow that I'm struggling with. How to make the NPC actually interact with the object.
The thing that I'm actually stumped on is I want to have a lot of objects that use this framework, and many with different functionality. Some will be picking up items, some will be dropping off items, and then some could be completely different behaviors like doing something on a computer or opening a container or whatever.
I dont know how I can attach a custom interact behavior to different objects and still trigger it in the same way for all of them
my rigidbody for my character's arms are moving even after the main body collides with a collider
so the arms fly away if i keep the joystick down
how do i prevent this
Well you would have to explain how everything is set up for us to answer that
That should probably be defined by your tasks/jobs/actions.
The interaction action should probably be queued even before the npc starts moving. After all, if there's no interactable target, there's no where to go to.
That is fair. That was more for the case of "I reached my area but something pushed me out of the way" or some cases like that, if something prevented the NPC from reaching the thing they thought they could reach
Ai brain takes the world context and decides what action to do -> queue desired action(like interact) -> queue any dependency actions(like move to interact position) -> reverse the queue -> agent executes the queue.
its the actual code behind "queue desired action" that gets me
before I was thinking store a reference to the interact method in a scriptable object
agent.EnQueue(action)
but I dont know if thats actually possible

oh?
what kind of agent is that? looking for the api docs on it
The action would be constructed at the planning stage and include reference to the interactable object(or whatever else context it needs). Then, when it's time to execute it, it would use this context.
Whatever you implement.
There's no built in agent for that.
oh agent being a custom thing with your own queue
ok I see
got confused with the existence of navmeshagent
Yes, with anything related to controlling the npc/character.
Many ai frameworks use the agent word for the same/similar thing. Basically an entity that plans and/or executes actions.
In case of navmesh, it's handling the navigation.
the arms have a rigidbody and the whole character has a rigidbody
and when my code moves the character as a whole
but then the arms go flying off
ANd how does your movement code work
and how are th things connected, wth joints? Active ragdoll?
That's not super helpful
they're just bones
what do you mean "they're just bones"
This sounds like an active ragdoll setup based on the limited information you've given
you'd have to make sure you're moving your character via appropriate physics calls, and not by moving the Transfrom directly for example
That explains how they are rendered, not how the whole physics setup works
well i made bones for the body
in the editor
idk what else u want me to say
ok so move the rigidbody and not the transform
I want you to talk about how the physics of it all works. Or show some screenshots, or anything
But yes, don't bypass the physics engine, and physics will work.
Active ragdolls are not generally simple
i just want to know if i can prevent body parts from flying off
They should be attached to the main body via joints
And everything should only be moved via the physics engine
then they won't fly off
It's confusing to me that you're talking about making bones and having Rigidbodies and everything and you don't know what joints are
how did you get to this point
Anyway it's tough to help you since you're providing so little detail about your project
Then you skipped a few steps.
Like a few very big and important steps.
does it matter if the arm bones arent connected to anything?
or do bones not even matter
will the joints be connected from a distance?
Bones don't really exist in unity. At least not the same way they do in blender.
If they're not connected - they will be separate, naturally
but yeah bones aren't a thing
which is why I asked what you meant by that
They're a thing in 3D rigging, but the form they take in Unity is not actually as anything called a "bone"
Same for 2D sprite rigging.
But again I can't even tell if you're using that since you still haven't shared any details about your project
i cant really share it cuz it's all over the place
id have to put up like 5 different screenshots
Maybe also just explain what you're actually trying to do
It's confusing to me that you're using multiple Rigidbodies
Are you just trying to make an animated character?
Or are you trying to make an active ragdoll game
its cuz im using fixedjoint component for sticking the arms to my weapon
and it requires a rigidbody by default
Why ar eyou using a joint
to attach the arms to your weapon (or vice versa)
Things don't need to use joints to rotate
unless you're trying to simulate physical realism with the rotation for some reason
i can do it in code but thats too complicated
Trust me the path you're going down is going to be way more complicated
rotating things in code is very simple, once you understand it.
the component is there for a reason man
Yes, the reason is for physics simulations
But, you do you
I was just trying to help.
Maybe you could read this: https://learn.unity.com/project/goal-driven-behaviour
In this project you will learn about the Goal-Orientated Action Planning (GOAP) architecture used to create intelligent agents that can set goals and plan at achieving them. Unlike Finite State Machines, actions and states are uncoupled, making for a very flexible system. You will build a GOAP system from the ground up and implement it in a si...
have u guys seen the billion dollar code
they really made it interesting
i feel like an entrepreneur after watching episode 1
i can relate
to the crunch
even tho ive been working on this game for 10 fucking years
on and off again
god i hate having a full time job
to pay for food
and gas
indie is so hard man
why are you thought dumping on here
Is there any library out there that does this? All I found so far is overkill stuff for 3d meshes like greedy meshing
I feel like it should be simpler for 2d
When I can 100% ensure everything will be coplanar
Hi everyone, I am implementing roll mechanic in the game, the movement worked fine, but the roll animation is playing twice(I am using trigger to play the animation), I don't know why, I am tried checking using GetCurrentAnimatorStateInfo(0).IsName() method, but still animation is playing twice. Here is my code
if(!playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("Roll"))
{
Debug.Log("Rolling");
base.Move(swipInput, rollMoveSpeed, rollRotationSpeed);
HandleRollAnimation();
}
private void HandleRollAnimation()
{
//Debug.Log("Playing roll animation");
playerAnimator.SetTrigger(rollID);
}
What are you trying to accomplish with this code?
Actually I am trying to implement mechanic similar to dash mechanic.
Actually what I want is that I want to know whether animator has set the trigger or not.
Your code is confusing to me because it seems like it's saying "If I'm currently playing the roll animation, trigger a roll"
๐ Large Code Blocks
Use 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 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.
Let me send the code again.
just edit your post
I have edited it.
so what is the context of the code
The if part is inside FixedUpdate
Basically I am trying to avoid to make roll mechanic run twice.
Sorry for not understanding the question.
hmm. should be ok. can you reinstate the debug and then screenshot the console
Okay. I will.
no, your first answer was completely correct
I was looking for this.
//Debug.Log("Playing roll animation");
also uncollapse the log
So why no Playing roll animation ?
omg. Now you've taken out the Rolling
Ok, so there is obviously a delay between you setting the trigger and the animation running thus causing you to constantly set the trigger. So you will need to implement a bool to stop you doing this
Okay, thanks for the help, I will try to implement that.
shouldn't be too hard.
add a bool
check it after the if
set it in the if
add an else to your current if to unset it
Thanks
Can someone help me figure out what is going wrong with my rigidbody controller?
public void SetVelocityWithMomentum(Vector3 incomingVelocity)
{
// Ignore y velocity when calculating the desired change in velocity
incomingVelocity.y = 0;
// Calculate the desired change in velocity
Vector3 desiredVelocity = incomingVelocity + currentGroundAdjustmentVelocity * acceleration;
Debug.Log($"incomingVelocity: {incomingVelocity} currentGroundAdjustmentVelocity: {currentGroundAdjustmentVelocity} acceleration: {acceleration} desiredVelocity: {desiredVelocity}");
// Example output while holding W key:
// incomingVelocity: (1.35, 0.00, 2.68) currentGroundAdjustmentVelocity: (0.00, 0.20, 0.00) acceleration: 4 desiredVelocity: (1.35, 0.79, 2.68)
rb.AddForce(desiredVelocity);
Debug.Log($"Actual Velocity: {rb.velocity} Current Speed: {rb.velocity.magnitude} Desired Speed: {desiredVelocity.magnitude}");
// Example output while holding W key:
// Actual Velocity: (0.00, 0.00, 0.00) Current Speed: 0.001517748 Desired Speed: 3.103522
}
As you can see from the debug outputs, its not gaining any momentum at all. The rb's mass is set to 54, but even when I set it to 1 it gains as such a low rate that its nearly pointless.
Debug at 1 mass, while sprinting (doubling the incoming velocity):
incomingVelocity: (2.32, 0.00, 5.53) currentGroundAdjustmentVelocity: (0.00, -0.01, 0.00)
acceleration: 4 desiredVelocity: (2.32, -0.03, 5.53)
Actual Velocity: (0.00, 0.00, 0.00) Current Speed: 0.001421971 Desired Speed: 6.000091
// Calculate the desired change in velocity
Vector3 desiredVelocity =
lmao
no shit
you have to show where the function even is with the complete !code in link
๐ Large Code Blocks
Use 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 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.
I dont see why you need the rest of the code, I literally am outputting all the variables used. Nothing else in my code modifies velocity on the rigidbody.
rb.velocity doesn't get updated immediately when you call AddForce
it gets updated during the physics simulation
If you want to do it in a way that is visible and mathematically equivalent you can do this:
rb.velocity += desiredVelocity / rb.mass * Time.fixedDeltaTime;
note that desiredVelocity is a confusing name for a force.
Yeah I agree, it was a remnant name from testing various different methods.
So I guess my confusion is that I was under the impression that you aren't suppoed to modify the velocity via: rb.velocity but to use rb.AddForce. In addition I thought it would cummaltively add the force the longer the velocity was applied.
modifying the velocity with += or including the current velocity in the calculation is equivalent to what AddForce does
this makes it a cumulative change.
huh? just wanted to see where method was called.. providing context wouldn't hurt but np.
The "not supposed to modify velocity" instruction is mostly about setting it to something that doesn't take into account the current velocity at all
In addition I thought it would cumulatively add the force the longer the velocity was applied.
This is true both about AddForce and doingvelocity += ...
For example if you do velocity = Vector3.forward * speed; this completely overwrites the velocity. That's the thing you were warned about
Gotcha that makes sense. I'll look into a bit more.
It's called in a fixed update
my webgl build seems 'slow' but still runs at 60fps, is there a way for it to actually slow down fps wise and not just the timescale and things like that?
or am I missing something
like I have a timer running and 1s takes almost 2s
I'm currently trying to make a small tower defense game, mainly inspired by Bloons, and I'm having trouble making a good way to get the enemies' movement path to work well. All tutorials I've found so far have just placed "checkpoints" and having the enemy move toward the next checkpoint whenever they get close enough to the previous one. This doesn't work for me, both because it can mess up at very high speeds, and because I'm trying to make enemies that split into multiple smaller enemies when killed. When this happens I don't want the smaller enemies to just spawn on top of each other.
Like, if an enemy splits into 2 I want one to spawn slightly forward on the track and one to spawn slightly back, but I can't figure out a good way to accomplish this, at least not with the current way I made the path. Does anyone have any ideas?
A spline library would be a good bet
Thank you, I'll check it out
not a code issue, but everytime I launch Unity and then open a script, it doesnt have the intellisense thing active. (like the autocomplete for GameObject etc) I have to keep going into the settings to reselect visual studio
Try updating the Unity Editor to the latest LTS
is that 2022.3.46f1?
It should say "LTS" next to the version in the install page of the Hub
Hi
Will having a giant texture on a material be a problem down the line? Talking about texture atlases here
Stiching all the tile textures into one big texture because that way I can draw everything at once, and I know for a fact I'm gonna be using the same material
I think some gpus actually have hard limits for how big a texture can be
hey i changed a setting in build settings(?) and I don't remember what it is but I no longer have Debug.Logs in Editor
I have all Full Stack Trace boxes checked and running in WebGL
anyone knows what the setting/where it is?
I am trying to jump to a time on a timeline, but for some reason when this code runs while the timeline is paused, it evaluates signal emitters in-between the current time and the time it's jumping to (that aren't set to retroactive). How do I avoid this?
As an example, imagine a timeline where this code runs at 10 seconds, there is a signal emitter at 15 seconds, and the marker it is jumping to is at 20 seconds. If the timeline is playing and hits 10 seconds, this code will correctly jump to the marker's time, skipping the signal emitter. If the timeline is paused at exactly 10 seconds, when this code is called to jump to the marker at 20 seconds the signal emitter at 15 seconds will be evaluated. How do I prevent this?
director.Pause();
director.time = markers[markerID].time;
director.Evaluate();
director.Play();
in the Player settings there's a Use Player Log option
ah
i need to run a build
so the settings would get applied in editor aswell
it seems
wait, are you actually referring to your logs not printing to the editor console rather than the log file?
also that's not really a code question
Yes, somewhat modern PCs should be able to handle up to 8k or even 16k, but mobile GPU could be limited to 4k. You'll need to research the target devices you're aiming for.
@marble totem Not a place for requests. If you have an actual question about learning Unity, ask away.
Also this is a code channel
I had an actual question about learning unity, my question was how do i export a fully rigged fbx file to roblox studio
that sounds like a question about roblox studio not unity though
And this is still a code channel
bruh i know how to use roblox studio, i dont know how to use unity. My question doesnt need any knowledge of roblox studio to answer. Only unity.
no one is answering since it makes no snese without the context, Unity is not a DCC app you dont export fbx files from it
There's little reason to author content in Unity for export to other apps, unless it's for further authoring in Unity, or you've got a virtual production pipeline. None of which this sounds like
or unless its for like making a asset bundle for something made in unity, but that is rare and i would still look at the docs for that thing not unity
its a unitypackage file
thats why i have to shove it into unity first
I mean there is a supported way to do it. Just the question was posed as a job request and still in the wrong channel. Also simple google search would answer that. Extremely lazy and off-topic.
lil bro u have no clue the issues im having u sound like such a nerd, ive used google, ive watched videos do u seriosuly think my first thought when i have an issue it to look up the officical unity discord and ask a bunch of condisending nerdy moderator to answer my question. The FBX is in a complex format, rigging, materials, animation keyframes are all seperated from original FBX model file. honestly bro gets moderator and just goes to his head.
!mute 887086739846479902 3d rude as well. Take some time to read server rules.
awvm was muted.
you are acting like a child when people are only trying to inform, and pointing out the question is off topic and lacks enough context to be answerable
If it's an FBX that just happens to be in a unitypackage file then it's just an FBX and this has nothing to do with Unity. If there's more stuff added to it all of that is Unity-specific and cannot be exported. (You may have luck with the FBX exporter, but that's unlikely to be relevant).
This is a programming channel for Unity. None of your question relates to that, so it's no surprise you're getting a response like this
"lil bro"
as if you aren't 12 years old.
I have n 2D points in clockwise order, which each connects to the origin and thus they divide the plane in n parts (think a pie chart). Given a target point, what's the easiest way to tell which part it's in/test if it's in a certain part?
if its like a pie chart, you should know what angle each starts and ends out
can make a direction from the origin and given target point and get its angle
Testing angles is kind of annoying though because of wrapping around.
modulo to 360 should help with that unless one of pie pieaces goes over the 0 point
other way could just be treating each area like a triangle and testing if the point is in any of them
i forget that math for checking that manually
but you could use like a PolygonCollider2D and its OverlapPoint method
Yeah I'd like to do that with pure math.
The points can rotate around and the only guarantee I have is that the points are in order. So even after moduloing them, the first point could have an angle of 350 degrees, and the next point could be 7, and checking if an angle is in between or not still seems a bit annoying.
I guess one approach is to normalize the angles to a strictly increasing manner, and also normalize the target point's angle to be larger than first point's angle, then comparison could be done without worrying about wrap around.
yeah mentioned that first since solving as a trinangle is kind of a pain
how could i make something where theres like the us map with states and i can click on each state for info and interaction options
Use Photoshop to split the map into 50 images
yeah split it up, or draw polygon colliders over it
so after i split the map and put them individually into the project how would i make it select that state's stats and interactions instead of the other ones
Put a script on each with the state information
Need a bit of analysis. In this video, I'm placing my mouse over a specific part of Earth, and as I zoom, the camera slowly pans over to that location centered around the mouse. What's the math behind this?
I guess, current orbit position lerping towards a normal up position above that location in a specified distance
Could be something like that but the zoom out is something that I'm wondering how it would be able to inverse that behaviour
One thing I'm wondering is whether it would simply work by zooming in by moving the camera straight towards the earth and rotating the camera right amount to keep the cursor pointing at the same point on map. To help calculate that rotation, it might be easier to try to figure out the amount you need to rotate the earth to keep the cursor at the same point and just inverse that rotation to get the camera rotation
I am guessing, the target spot the camera is point to is also just a lerp between center of earth or current rotation towards the final spot. Botht he movement and target lock are then animated from 0-100 percent in parallel to give you this smooth bidirectional movement.
Mathf.DeltaAngle could make that easier
Doesn't linerenderer follow the parent position if its a child of the paren?
my distance joint isnt working
Depends on the Use World Space option
is anybody alive out there
Doesnt seem code related, try #โ๏ธโphysics
And provide more info
you cannot expect anyone to answer when all you say is 'isn't working'
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Hey is it possible to create animated rule tile?
what movement type is good for when I want to add 2 different movement forces to the same object?
I'm trying to make an object that slowly pulls other objects in, but these objects are all also trying to get to a different point, how would I go about doing this?
If your using rigidbodies, you could use AddForce to add a directional force onto the current velocity, or you could control adding velocity yourself, I do something similar for effects in my game where I have a "move" velocity controlled by player input (in your case, it sounds like it would be controlled by AI logic) and then I can += a "influence" velocity and either drop it over time back to 0, or have something like a debuff set it to 0 when it ends, so it may be something like rb.velocity = move + influence; influence = Vector3.Lerp(...);
Hmm somethings not adding up for me here
the lerp is the distance between the black hole and the object right?
and the move is the original movement betwen its current position and its destination?
no, lerp is
current = start, end, t
where t = % of difference between start and end expressed as 0-1
no, t at 1 would return end
so, yes...
Lerp(a, b, 1) just returns b
yeah
Lerp(a, b, 0) just returns a
alright I got it working in a smooth way, just need to figure out how to reset the influence, cuz its stacking forever whenever they come back into contact with the black hole
how do you reset it to 0? it just keeps stacking until they're just fully stopped whenever they touch the black hole again
Since its a separate variable you can affect it differently, you can drop it over time or just set it to 0 whenever your black hole end condition is met, it could be by directly changing a public variable, or what I do is use a public function or property to change it from other scripts
They said they'd drop it to zero over time so you probably could do so with Vector3.MoveTowards and slowly move towards Vector3.zero.
I don't know what it is I just cant do it
im trying everything but the speed just keeps stacking
they're also no longer going into the black hole but being repelled by it
though i dont think its because i got the Vectors mixed up i think its something to do with the objects distance from world 0,0,0
I have this "chunk" of integers here, which is a blank canvas for my procedural road script to create road on, so moving one tile up would be done by subtracting 8 from the current tile, and down, would be to add 8 to the current tile.
My question is, now that i am making it detect if it is near the edge of a chunk, how would i do that with the left and right edge? - I did it for the up and down, by checking if the length of the array is longer than current tile + 8 for down, and same with "- 8" for up, but how could i do left side check when it can be all the numbers: "0, 8, 16, 24, 32, 40, 48, and 56"
should i just check if the currentTile incremented with one would be divided by 8 with a remainder of 0 ?? or does that have some issues as well??
If you can, you're better off using a 2D array: int[,], so you can access the elements like arr[row, col] and avoid the tricky math
i would rather not xD - each of these numbers will be changed, and each of those numbers it will be changed to has properties that i have allready built
there is no left edge in this scheme. index 8 is just the first element of the second row
Or I guess you're asking if the column is 0 or 7?
wouldn't it be:
int width = 8;
int height = 8;
int row = index / width;
int col = index % width;
```?
then it's just bool onHorizontalEdge = col == 0 || col == height - 1;
likewise bool onVerticalEdge = row == 0 || row == width - 1;
You can convert XY "coordinates" into a single-dimensional index using the formula idx = WIDTH * y + x assuming Y goes down (rows) and X right (columns)
yeah that's the reverse calculation:
int index = width * row + col;```
the rest of the row & column navigation is pretty much made by now, so i just wanted to use math for this last little detail. The script will move out procedurally from around the center point, in increments of one row/column at a time. so if i can just with math calculate a list of numbers that would make up the left and right "edge", using the width of the square
Why if I wrap serializable fields with #if UNITY_EDITOR and build I sometimes get an error which says that an scripted object has a different serialization layout?
- Why it's sometimes and not always?
- During building the game, I thought unity recompiles the scripts and reserialises the assets, if that were true then this error should not appear and they field would be filtered out. ๐ค
(As a side note, a single dimensional array where you do your own index conversion is obviously the fastest, but even jagged array is faster than multidimensional array. Not that I would suggest choosing base on performance, the difference between these are negligible in most cases)
Sure I've given the simplest way to do that I believe
- I thought it was always honestly
I have several classes which uses that and I don't run into problems, until today where I'm starting to get this error...
As far as I know that's always been disallowed.
the manual says otherwise, which is... fun
Unity documentation says something about this? Where?
I'm now very confused
i have an fbx prefab imported (i ensured the axis are exported correctly). I want to apply a rotation via script to a gameObject inside that prefab. the problem is it is acting erratically. meanwhile if i try the rotation script on a cube, it works as expected.
does anyone know if there is something native to fbx that is causing this issue?
what does "erratically" mean
show the code, and show what ahppens
not likely to be related to the FBX, no
my best guess is it has a pivot point way out in space so a rotation of 1 degree looks like a move of about 2 meters
the prefab has the location -46, 0 -35. but all the objects are 0,0,0
location data for each child
all at 0,0,0 except the prefab. but i dont even think thats an issue
You need to set this to pivot
if you want to see the real locations of the objects
ok , yes the pivot is way off in the distance. but i feel like i can find that in script then translate it over to where the red sphere is on the door.
like find pivot and center in script then move pivot to center and use it for rotate.
Basically three options here:
- The best and cleanest option is to fix the pivot in Blender and re-export
- The next best option is to add an empty parent object for the object, and place the empty parent at the desired pivot point. Then offset the child locally until it's visually in the right place
- The worst option is some crazy math in your code
ok. ive seen one in twinmotion thats kind of like 2. but i was trying to avoid that. i'll look up the blender way.
What would be the best way of doing multiple string comparasions? I have a param of readonlyspan<char> and I want to do different things if the param is "b", "uppercase", "u", "lowercase" etc
depends what you want to do in each case
a loop, a switch, a series of if statements, a Dictionary
any of them could work and be elegant, depending on the circumstances
Check out StringComparer.Create(), you can pass a culture and a variety of string comparison options (ignore case, ignore symbols, etc.). You could pass an instance of that into your method and use .Compare(s1, s2) to do the string comparison
I am using a kinematic rigidbody for the player and a dynamic rigidbody on the ball.
Another thing I don't understand is why hitting the ball horizontally doesn't apply any of the things written in the script (speed, bounce, animations). It is as if only the collider is applied
does anyone know if its possible with custom editor stuff to get this graphic from the rule tile
I can't really find anything about what type of field this would be at all
I dont think it is exposed, but ask in #โ๏ธโeditor-extensions
okay!
My code is this:
Im making a spaceship that shoots bullets, but it dosent work
Does anyone knows?
Line 25 is referencing something that doesn't exist. Presumably because you have no "Cannon" object in your scene to actually find.
Also this is a #๐ปโcode-beginner question at best.
okay
you can just check if the y < a certain amount and if so then just add a default amount that would make it go towards the enemy?
Hmm, more of a math question than code one so not sure if this is the best place for it.
Let's say I have some triangles where I know when they are rendered on screen, any pair of two triangles will not intersect. In other words, choose any two of the triangles, one of them will be in front of the other.
Is there a value I can assign to each triangle, such that when I take two triangles I can use their values to determine which one will be in front?
Like - based on the vertex data or something?
Could you calculate the centroid of each of them and use the distance from the camera to the centroid?
Yeah I have some triangles in the form of triplets of vertices.
I thought about using distance from camera to center of each triangle, could work but was wondering if there are other ideas.
Square distance to the centroid ๐
I have 2 rotations and I want to move along it by X degrees, what method should I be using?
Not sure what you mean. You want to move between those two with x degrees change?
First Quaternion.Angle to get your degrees then Quaternion.Slerp or Lerp to do the movement
This seeeeems to work alright.
Vector3 axis = Vector3.Cross(vec1, vec2);
transform.rotation = Quaternion.AngleAxis(degreeOffset, axis) * transform.rotation;
https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
If rotating by a certain amount of degrees, there is a built in method
So for context, I'm trying to make a system where you can zoom into a sphere. The point that your mouse is hovering determines the "center" of the zoom.
hi there guys, did anybody face the issue with TMP and addressables, when you load a bundle with prefab which has TMP it shows pink text?
I think I need a sanity check, because sometimes the zoom is a little off. Though I'm unsure if that's a problem with the sphere collider or my own code.
Probably my own code.
void Update()
{
var delta = Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
var newScale = Mathf.Clamp(currentScale + delta, 1, 100);
var input = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z);
Ray ray = Camera.main.ScreenPointToRay(input);
if (Physics.Raycast(ray, out var hit))
{
var angle = Vector3.Angle(Vector3.back, hit.normal);
var arcLength = Mathf.PI * currentScale * (angle / 180);
var scaleFactor = newScale / currentScale;
var arcOffset = (arcLength * scaleFactor) - arcLength;
float radians = arcOffset / newScale;
float degreeOffset = radians * (180 / Mathf.PI);
Vector3 axis = Vector3.Cross(hit.normal, Vector3.back);
transform.rotation = Quaternion.AngleAxis(degreeOffset, axis) * transform.rotation;
}
sphere.localScale = Vector3.one * newScale;
sphere.transform.position = Vector3.forward * newScale;
currentScale = newScale;
}
I suggest putting some debug lines there to know where your target position of the camera is and where your target rotation looks at. I am also wondering, if your target rotation is straight at the point of the hit at the "earth". So it will show slightly off until you reached the positino of the marker with your camera and wont see anything ๐
That blue cylinder you see is using the hit.point and hit.normal properties to position and align itself.
Fits with the mouse.
If font asset is not included in bundle and was not referenced anywhere, it might not getting included in the build.
Yeah, but the zoom final position of your camera is the hit.point or something with offset above the hit point normal?
Nah nah you misunderstand. The camera isn't zooming in. The sphere is just getting bigger.
Optimal illusion.
Not on pc so I cant really check through this, but a lot of this can probably be reduced by using built in functions.
definitely some of the radian/angle/arclength conversions.
I find doing your own trig can pretty much always be avoided
but that's half the fun
If you just learned what a trig function is maybe, I prefer to use methods that directly solve what I need
Ah okay, but the outcome is the same. if you move the camera or the sphere rotation and scale, the calculation has got its points of start and end(your hit.point). So I would test doing the cross not between the hit.normal but hit.normal plus some offset to scale the normal up vector.
font is included i think cause i see a reference in the editor inspector, you can see it as well on the screenshot i posted, but it seems this font is broken in some way
or maybe it missing shader or material, idk
Are there easy methods to create functions that replicate what Gizmos do but for builds? so you can turn on some debug lines in a game build?
You have to build it out yourself with line renderer or procedural geometry. There are also assets that facilitate those for you.
With procedural geometry i assume you just need a game object with a meshrenderer and modify that mostly right?
building out custom shape from vertices into procedural mesh
yeah, i mostly just needs some lines and circles, that should not be too hard i think
If you need this for 2d only you can just shape spriterenderer calculating how to scale it and use other primitives as well
I am using it for 3D, it's mostly to visualise some forces and direction vectors for a vehicle
Could shape simple capsule objects for that then. As line renderer doesn't always look right in 3d
yeah, i was thinking of a sort of mesh with a thickness to represent the line and circles
As unitys default meshes are 1:1m , you can just use a box with thin sizes except the one you gonna extent and make a line out of that pointing at your target position and the scale you prefer.
Hi, I'm trying to batch render the blocks of a grid:
void SpawnGrid()
{
for (var i = 0; i < GRID_SIZE; i++)
for (var j = 0; j < GRID_SIZE; j++)
SpawnBlock(i, j);
}
void SpawnBlock(int i, int j)
{
var o = Instantiate(BlockObject);
o.transform.position = BlockPosition(i, j);
o.transform.localScale = BlockScale();
o.isStatic = true;
o.GetComponent<MeshRenderer>().sharedMaterial = BlockMaterial;
}
however the batches count is +800
are you expecting them to be static batched? i don't think just marking them as static is enough if you spawn them during runtime: https://docs.unity3d.com/Manual/static-batching.html#runtime
I already tried StaticBatchingUtility.Combine but I can't dupplicate the gameobject BlockObject without spawning it in the scene
aren't you spawning it in the scene in the code above?
parent your instantiated objects to an empty gameobject and use that in the Combine method
Still batches +800, I will try merging the meshes together manually, then only instancing one gameobject
ok I managed to merge all meshes together and render them as one gameobject only
now I got 9 batches count, the fps changed from 240 to 240 ๐
some useles optimization here
that fps in Editor or Build?
these ones
So in Editor. Editor fps is meaningless, the Editor itself has too much influence, Built fps is the ONLY one that matters
ah ok, predictable, btw is this even batch rendering? I just merged all the mesh together manually
I'm not even sure it's batch rendering at this point
Hy everyone! I'm asking help for my game project, can i ask it here?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
you wouild need to look in the profiler
I make a game with ennemies helthbar, all work. But when I add more game featurs, ennemies healthbars strangly stop working! skript seems good and no console errors, can someone help me?
see #854851968446365696 for what to include when asking for help
what do you mean? the batches count is at 9 despite the big number of blocks I spawned, the point is: is this how batch rendering operates under the hood? is it a "merging meshes together and doing only one draw call" or is it rendering multiple objects and doing only one draw call?
Yes, that's how batching works.
If you need further performance troubleshooting, you should use the profiler to identify bottlenecks.
Hey, i am struggling with this particular Orientation problem, I want the character's Up and Forward axis to return to normal but also apply the additional rotation, this code seems to do this but the additionalRotation is applied in the wrong direction
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.
I think it's a problem with how the rotations are being combined but I'm unsure of the best way to combine them
The paste link is not available
i'm trying to make snake on this system.
when the object collides with one of the squares, that same square turns on the light to the right colour. red for food, green for head and yellow for the tail.
when the object enters the collision of the square, it changes the colour to the right colour (red, yellow or green), and when the objects exits the square, it changes it back to 0/off/white.
however as visible in the video, it turns on and off the lights at the same moment. causing it to be inconsistent if the light is on or off.
i'm using the following code:
public int LightX = 0;
public int LightY = 0;
public int LightLevel = 0;
// Start is called before the first frame update
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
LightScript.SetGridButtonLight(LightX, LightY, 0);
GetComponent<SpriteRenderer>().color = Color.white;
}
else if (collision.CompareTag("Red"))
{
LightScript.SetGridButtonLight(LightX, LightY, 0);
GetComponent<SpriteRenderer>().color = Color.white;
}
else if (collision.CompareTag("Yellow"))
{
LightScript.SetGridButtonLight(LightX, LightY, 0);
GetComponent<SpriteRenderer>().color = Color.white;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
LightScript.SetGridButtonLight(LightX, LightY, 1);
GetComponent<SpriteRenderer>().color = Color.green;
}
if (collision.CompareTag("Red"))
{
LightScript.SetGridButtonLight(LightX, LightY, 3);
GetComponent<SpriteRenderer>().color = Color.red;
}
if (collision.CompareTag("Yellow"))
{
LightScript.SetGridButtonLight(LightX, LightY, 5);
GetComponent<SpriteRenderer>().color = Color.yellow;
}
}
does anyone know a solution to this?
setting the light happens in a separate script. however until the tail got introduced i didn't have a problem with this.
this is pretty cool ๐ I have a Ableton Push myself but wow interesting usecase
thanks, the first thing i did was make it in a sort of drawing tablet:
press the button to go through the colours
wow. Does unity read these inputs as regular HID device or ? serial?
however now that i'm actually making a moving game, i have the above problems
will check it out and see if I can come up with something
i'm using the input system together with a plugin called MINIS from keijiro for the input. which is really easy, and for output i use wetdrymidi on the asset store, however i sadly had to use chat gpt to get the output working, thanks to which i don't know enough about the system to directly couple the input to the output
Oh i see, so the light grid is just an X,Y coordinate.
yep. i'm using the following script for the output
(it's too long for discord. 1 sec
so the tail growing keeps flashing whilst moving , thats the issue?
here use one of the linkshare websites !code
๐ Large Code Blocks
Use 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 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.
the segments of the tail are randomly on or off. on the pc version this doesn't happen
!code
๐ Large Code Blocks
Use 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 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.
okay so the LED matrix is just a simple 2d array. Ok so you only set positions OnTriggerEnter it seems
or is there a movement script that updates each motion/ key stroke
and with OnTriggerExit I reset them
which object has this trigger though
there is a movement script. but it doesn't interact with the lights
the squares each have their own trigger
oh
when someonething with one of the tags collide with those the colour changes to the one with the same tag
so i have a 'red' tag, a 'yellow' tag and for the player i have green 'player' tag
so i use compareTag for that.
the same script works on PC ? because using triggers is not something i've seen before with a snake game
from what i see, it fires both enter and exit at the same time, because both something enters and exits the square.
the triggers is only for the lights
let me quickly make a gameplay video from pc
I feel like thats what might give off result, need to prob see how you move the snake as well , thats very important for accurate detection for physics (triggers)
for the movement:
i set a vector2. to one of the directions using the buttons in fixed update. and then i lowered the fixed update amount to about 0.25
I would probably just update the LED matrix every move made. I would not use triggers or physics, esp the 2D representation working fine
assuming you are moving this with transforms directly or something ?
normally yes, this is just a prototype.
let me check
yep. transform.position
I wouldnt use physics for this at all, some array/2d array would do
yeah moving too fast that wont give very accurate hit results
with a mathf.round to make sure it's a full int
yup agree and 2D array is already there too. Just update the ones that represent the gameplay pieces to the LED matrix mapping
i'll just have to figure out how. i'll take a look at it.
not to used to coding things like this
you would at very least switch it to rb.position (rb being Rigidbody2D component)
but yeah physics here is overkill and prob more harm than good
could you send the movement code in link as well
is on it's way
i don't use the rigidbody and movespeed, which are in the script as something i removed
yeah rigidbody is the physics component, right now you're teleporting it skipping the physics
sometimes it catches up in time though so it does detect
you normally let rigidbody move your transform into place, instead of other way around
the green is always consistent on the screen. it's only the ones that come after that that get confused and randomly decide to be on or of each movement
screen = board
just one of those luck of the draw things lol
yep.
guaranteed if you code the leds to match whats already happening in the 2D space you wont have issues
is there a way to delay either the 'onentertrigger' or 'onexittrigger' ?
you dont even need triggers
You could just signal an event or just tie the LED script into movement
i'll take a look at both options. thanks a lot
you already have the positions of yellow, green and red no? you just update them on the led board each movement
might have to create mapping function like v2 to your 2d array matrix
so first check the locations on the grid, and then update the lights
yeah first you want to make your current movement move on a 2D array board
i'll have a look at it later tonight. i have to go now. i'mma save all of this
sure thing! If you want there is a thread you can make I can come back to it later to, I have led board I can test some stuff on and send you any info that might help
I can't seem to find KeyCode.Section
whats "section"
ยง
https://pastebin.com/Nkj3GX4x Sorry code 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.
Keycode "section" of the docs?
https://docs.unity3d.com/ScriptReference/KeyCode.html
Alternatively, how to get location based KeyCode input?
oh thought that was calld SubSection
Either way I can't find it
I don't even know where that is on my keyboard
facts
lol
you prob need to store it else where
Hm... Can I put the keycode based on layout location?
no
By that I mean, I'd like to set KeyDown to Location of tilde
Since Mac blah blah
Don't think you can change the enum bindings
as I think each keycode is a ascii representation
there's an option to Use Physical Keys in the input settings
How would that work when I am programming for mac and windows?
why not read the docs and find out https://docs.unity3d.com/Manual/class-InputManager.html
Ok so I am getting this error:
"Object reference not set to an instance of an object"
Very standard error
!code
๐ Large Code Blocks
Use 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 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.
also you havent said which line that error is on
probably wont be anything revealing you can't see on your own
line 40
whatever is on line 40 is null then ๐คทโโ๏ธ
it is on this line
BlackHoleData[i].x = stageManager.BlackHoles[i].x;
stageManager or BlackHoles[i] is null
presumably there was nothing assigned to that index of the array
yes because I am setting it right now
where
no you're attempting to assign a float to x
on/from an unkown/null object prob
ok so give me a sec
at the begging of the code i set
public BlackHole[] BlackHoleData;
is this a private array ? did you actually initialize it
where
[System.Serializable]
public class BlackHole
{
public float x, y;
public float size;
public float radius, pull;
}
at the bottom of the script
alright so whatever is at index i its null and not blackhole
then I do
BlackHoleData = new BlackHole[stageManager.BlackHoles.Length];
for (int i = 0; i < BlackHoleData.Length; i++)
{
BlackHoleData[i].x = stageManager.BlackHoles[i].x;
}
you know you can just share a link to the full code and we can actually read it ourselves, right? you won't have to share individual bits
would you look at that, i was exactly right. there is nothing at index i in your array
i sent it here, I thought you could read that...
but now that I see it again do you have to download it to see it?
if thats the case I will sent a paste bin
notice how the bot message almost directly below that tells you how to correctly share code here
and on mobile it don't work thats why they link the sites
well obviously, but no one ever had a problem when I shared code like that before...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
okay well the issue remains the same, you have not actually put an instance of BlackHole into any index of your array, therefore every index contains null
same goes for your Obstacles array
all you need is new() in your loop and make new object each loop
Oh right
in fact, literally all you need to do is just BlackHoleData[i] = stageManager.BlackHoles[i]; like you're doing for PlanetWeights, unless you need separate instances for whatever reason
oh yea much easier ^
Thanks for helping with my issue
That fixed it
but I prefered this approach
the problem is that I have 2 identical BlackHole classes. One in the script I shared and one in me StageManager script. Is there a way to make them "Global" in some way?
just don't redeclare the same class
But then I will need to reference it in my other script in some way
what
do you mean you have two instances of the same class?
Oh wait. My current BlackHole class is inside of my StageData class
Yep that was the issue
which means outside of that StageData class it's name is StageData.BlackHole not just BlackHole. either declare the class outside of StageData or use the correct name when trying to use the class in other objects
instances of a class is not the same thing as two copies of the same class declaration nested inside of two separate types
no I had 2 identical classes inside 2 different classes
Like this:
public class StageData
{
[System.Serializable]
public class BlackHole
{
public float x, y;
public float size;
public float radius, pull;
}
}
and
public class StageManager
{
[System.Serializable]
public class BlackHole
{
public float x, y;
public float size;
public float radius, pull;
}
}
why on earth would you do that?
To fix it:
public class StageData
{
}
public class StageManager
{
}
[System.Serializable]
public class BlackHole
{
public float x, y;
public float size;
public float radius, pull;
}```
HI,I need help
my new input system works on the editor but not after build and run, why?
it looks stupid but it worked so I kept it until now
Yes I realized that just after I asked
here ^
thanks for helping though
HI,I need help
my new input system works on the editor but not after build and run, why?
anyone help me pleasee?
see #854851968446365696 for what to include when asking for help
okay
As a general rule, if you EVER find yourself duplicating code, you are doing something wrong
my new input system works on the editor but not after build and run, why?
anyone help me pleasee?
thats all..
I tried some method on youtube but still didn't work. and also tried as in https://discussions.unity.com
I just don't know why??
the input wasd and more works in the editor but not after build and run
Here are the possible image that I know..
I don't know where the exact problem is
Anyone have any advice on controlling the timing/flow of a game when using an event based structure? Basically, the flow of my game is completely linear, so I need thinks to happen at specific times after other things have happened.
I currently have a game manager that manages the states (these are sequential and occur in series, with the exception of an idle state) and fires off different events sequentially in each state.
For example,
"SetUp"
OnShuffle?.Invoke()
OnDeal?.Invoke()
If shuffle completes after deal, then I have a problem.
If you're doing it sequentially, then you can use a coroutine that yields to other things that have to happen. That gives you full control of the order of things, while allowing you to wait for things like animations, etc. to complete for each part.
Yeah, I've tried that and async, I guess I just need to set up "finished" events so that the things such as the deck will send messages back to the game manager. I just didn't want to do that, as at that point you're essentially breaking the whole concept of the observer pattern
and then wait for the finished event using a coroutine
I wouldn't use events here, really
I would just reference the deck and stuff directly
That way you can yield return new WaitUntil (...) for them to do their thing/animate, before stepping to the next part
Or if they have coroutines, just yield return StartCoroutine(...)
I gotcha. I'll probably end up doing that. Thanks for your help!
ChatGPT came up with something kinda cool. Sorry to be douchie and share it right after you had suggested coroutines; but I still think it's pretty neat and wanna share it anyway lol
although doesn't work for passing parameters :/ you're right, direct references is the way to go.
This does work, I've used this method before specifically for a turn based game.
You create "Template" functions PlayerTurnSetupTemplate() , PlayerAttackTemplate and queue a bunch of events based on what you want to happen, then pass it to some manager that steps through each event that was added in the template.
But it does lead to a lot of switches/if statements, which is why I prefer to just do things directly.
You don't need to be fancy about it, just make it work for your game.
Hello, how can I make the input system easier to use? What ways can I follow to prevent the code from getting mixed up?
Why is it mixed up? Which input system are you using?
Easier to use than what? What are you doing now?
And what forms of "mixed up" are you looking to avoid?
In general, in every subject, UI, movement etc.
should i use events
That doesn't answer the question of how you're currently using the input system.
You should use events for things where events make sense.
You should use polling (reading input in Update) for things where polling makes sense
I'm not doing anything very important, I just want to make it go back and forth with WASD. Even if I want to do something simple, I want to proceed with the best practice.
Not sure what you mean by "important", but for basic directional movement my recommendation is to poll the input data in Update.
Since it is a thing that continually changes
biggest killer of creativity is premature optimizations
you optimize after your game is mostly made
or when all of your ideas are in fruition
I'm asking how I should write the code in terms of architecture, not code optimization.
If I report bugs in unity systems that are critical to my setup, is it usually worth waiting for them to fix it or should I start making my own parallel system?
Assuming my bugs aren't cool enough to get pushed to the top of the queue
well get your code to work first before you start to change it like so
if they're critical, just assume they wont get fixed, so make a workaround yourself
Have you ever reported and had it fixed? I'm wondering what the average timeline is for bugs that do get fixed
of course it varies wildly
I reported one, it got accepted, then 2 weeks later they said it was intended (clearly wasnt) and closed the ticket
You should find a workaround always
yes, normally 6 months or so. But a lot of bugs being repoprted for Unity 6 now are being flagged as wont fix until Unity 7
Oof
Took them only 48 hours to have a tester confirm my bugs existed so I was hoping for something speedier
I would not hold your breath. I have a feeling they will use Unite to announce Unity 6 production and thereafter only the most severe bugs will get fixed
Alright. Thanks.
This really depends on you and the people you work with. I would personally recommend against putting controls into lots of small objects. Like if you have twenty different types of objects you can interact with with "E" then don't put "if E is down" on every object.
Instead try to designate a key to something in something like a player controller and then send the event around. Makes it easier to control and prevent button presses from activating in certain situations.
where is AsyncGPUReadback?
Does anyone know how to access the position of the first knot in a spline container with the splines package? I'm trying to get the position from another script
Get the spline: https://docs.unity3d.com/Packages/com.unity.splines@2.6/api/UnityEngine.Splines.SplineContainer.html#UnityEngine_Splines_SplineContainer_Spline
Get the knot:
https://docs.unity3d.com/Packages/com.unity.splines@2.6/api/UnityEngine.Splines.Spline.html#UnityEngine_Splines_Spline_Item_System_Int32_
Wdym 'where is it'?
It's available since unity 2018.2
hey everyone
so i have a general question on coding, I myself know how to code however sometimes i may need a friend's help over a certain topic
example, I coded the player but he will code enemy for me, etc....
is this a good idea that i can stick to and end up making a successful game?
As long as you have organization yeah
Not sure what kind of answer you're expecting honestly. If you both code a successful game, itll be a successful game. If you both code a bunch of spaghetti, you have spaghetti.
Though if you dont understand what their code is doing at all, you more likely have spaghetti
Spaghetti can be successful games though lol
oh no i do, but sometimes it gets a bit overwhelming so a helping hand would help
I'm aware, the same can be said about a lot of things. Just chose it as a word to indicate something not good
helping hand for what?
for someone to code me something whilst i work on another part, example being modelling or coding something else
you want us to write you code while you model or something?
not sure we can or will do that but we can assist you along the way
not you, i have a friend whom im working with
i was just curious if it is a good idea to continue doing this of me doing part of something and him doing part of something
i mean you can if you want if it is working for you guys
if you are working efficiently the sure
if not, then probably not
we cannot really give you a yes or no answer, it is up to you to decide
do you have a question?
Are there any issues with networking in webgl builds? I was thinking of a side project using a socket-ish (Telepathy for C#) library and headless c# server, but it might be nice to be a web client. Obviously there's a host of other problems (load time, no access to file system, etc) but... I'm just in the daydreaming stage so none of that stuff matters anyway. ๐ FWIW I've built a mobile (and windows build) game with a server solution like this before so I could always go that route, but I'm just sorta thinking of the tech now
Another option would be a server that does everything with web based API calls but.. maybe makes for talking back to the clients harder without something like signalR
if I use mousedelta from new input system (inputmap action), do I need to scale it based on platforms/window size? WebGL window size is small
(Seems that WebGL pretty much doesn't allow anything in System.Net)
int numColliders = Physics.OverlapSphereNonAlloc(potentialPosition, AvoidanceDistance, terrainColliders, AvoidanceLayers);
if (numColliders == 0)
{
GameObject spawnedObject = Instantiate(spawn.ObjectToSpawn);
spawnedObject.transform.SetParent(transform, false);
spawnedObject.transform.SetPositionAndRotation(potentialPosition, Quaternion.identity);
positionFound = true;
spawnedObjects++;
}```
So I have a problem with a editor script such that instantiating an object like this does not seem to get caught by the next iteration's filtering. However, if I instantiate it all in one line such as:
```cs
int numColliders = Physics.OverlapSphereNonAlloc(potentialPosition, AvoidanceDistance, terrainColliders, AvoidanceLayers);
if (numColliders == 0)
{
GameObject spawnedObject = Instantiate(spawn.ObjectToSpawn, potentialPosition, Quaternion.identity, transform);
positionFound = true;
spawnedObjects++;
}```
It works fine, but the reason I don't want to use this method is because I want to instantiate prefab instances via PrefabUtility but that doesn't have the same instantiation parameters.
My guess is those additional method calls don't update till next frame when I'm looping over everything in one.
https://docs.unity3d.com/ScriptReference/PrefabUtility.InstantiatePrefab.html
This would be the method I want to be using, but as you can see there's no position or parent settings.
@latent latch you mean the physics thing doesn't detect it? If so, maybe you need to call Physics.SyncTransforms or something... Oh, actually you can probably also manually update RB.position/rotation (if you have such)
Ah, yep that was it. ty
takes a little longer but works ;)
@latent latch Also, depending on what you mean by "get caught by the next iteration's filtering", your SetParent(transform, false) is different than just passing the transform of the parent
(I don't think you want false for the 2nd parameter)
Yeah, I was toggling that back and forth but no go
what's odd though is it doesn't work in a prefab scene.
Need to drag the terrain out onto the main scene and run it
had to make my own billboard populater because the terrain's auto population doesnt work with spriterenders I guess
What is best practive if I have a script that adds a delagate to an action OnEnable but then potentailly wants to unsubscribe during update? Is there any problems with having both an condition -= as well as one on OnDisable?
Kind of like this:
private void OnEnable()
{
RunningSceneActions.OmPlayerPosChanged += ChangePos;
}
private void OnDisable()
{
RunningSceneActions.OmPlayerPosChanged -= ChangePos;
}
private void ChangePos()
{
if (activated)
{
RunningSceneActions.OmPlayerPosChanged -= ChangePos;
}
}
I can of course use the bool for a check on disable, just wondering if there are better ways?
not a problem, if there is nothing to unsubscribe then it does nothing except check.
Cool, thank you, it seemed to work but didnt know if it could cause some wierd stuff that i didnt notice
of course, with that code, you won't be able to subscribe again without disabling/enabling the script or calling OnEnable manually
Yeah that is really not a problem. Its just a collision detection thing that gets activated once the player is near, after that there is no need to turn it off again
btw, pretty sure OmPlayerPosChanged is a typo
haha
Yeah it is
Its not the actual code beeing used, just deleted a bunch of stuff to make the example clearer
Guess a added a typo
I'm using a Character Controller for an endless runner, you can control horizontal movement. I want to apply a small amount of rotation when moving left or right to make the movement feel more fluid.
My issue is that I can't really get the rotation amount to be framerate independent. On lower FPS there will be more rotation, and higher FPS will have less rotation. I calculate the horizontal movement amount in Update, use characterController.Move, then call SmoothRotate(horizontalMovement). I've tried various things, but still wasn't able to make it framerate independent.
private void SmoothRotate(float horizontalMovement)
{
float rotationAngle = horizontalMovement * rotationMultiplier;
rotationAngle = Mathf.Clamp(rotationAngle, -maxRotationAngle, maxRotationAngle);
Quaternion targetRotation = Quaternion.Euler(0, rotationAngle, 0);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
Here's the full test character controller code: https://hatebin.com/dqfnvbipgz
Weird, shouldn the delta time handle that?
Where does horizontalMovement come from?
Here's the full test character controller code: https://hatebin.com/dqfnvbipgz
What if you pass in a value to SmoothRotate that you dont multiply by deltatime?
Like SmoothRotate(direction.normalized * speed).x)
I believe that fixes it ๐ . Would you be able to give an explanation for my knowledge?
You are effectively passing in a target angle. There is no reason for it to be multiplied by delta time
Can't explain it better at least right now, I have barely woken up
With higher framerate your deltatime is smaller so your target angle got smaller too
At low fps you might be rotating towards 45 degrees but with high fps towards 10 degrees
Thank you!
Does anyone have any idea why this wouldnt go to the 2nd else if statement after the 1st one gets completed
When i click the button using the sapling (Currently holding 2) i get this. But when i change to the water pot (Currently holding 1) i get no response after clicking
hatebin doesnt seem to work for whatever reason so sorry for the picture
that is the way else works. Also not Unity code
So how would i make the statements go from the 1st to the 3rd in that order?
remove the else's of course
The problem is, it still doesnt work because i did that inittialy
of course if thats what you meant
I'm assuming this isn't Unity related since you're using Console.
The Unity server is specifically for Unity discussions. Try the !csds for regular C# questions.
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
I have created a helper script, which is supposed to shift the initial color's brightness.
Color.RGBToHSV(_initialColor, out float h, out float s, out float v);
v *= 1 + value / 100f;
_color = Color.HSVToRGB(h, s, v);
I convert it to HSV, change its value and convert it back to RGB.
Having a pure blue initial color, it properly shifts it to black on shift decrease, but stops at (0, 0, 0.7490196) (RGB 0-1) once shift reaches > 0, where 0 is the initial color.
Is there any way to properly convert it, since I'm sure pure blue adjusted with G and B at least seems brighter?
Correctly adjust color's brightness
So you guys know that there is the OnGUI method you use to draw gui on the unity game, right? So is there a way to make such a gui visible and interactable in VR? Without making entire gui as canvas and so on
no not likely.
Even Canvas Overlay doesn't work on VR doubt its much different
Can I refer to a scene as an object? I'm thinking something like:
public Scene myScene;```
And via the inspector drag n drop a scene in the field?
I've been refering to scenes by their name, but it's kind of a hassle for me.
no, you can use something like NaughtyAttributes or Odin Inspector which i believe both have an attribute to select a scene from a dropdown for an int or string variable. or you could write your own property drawer for it (i did this, it's not too difficult)
Thanks! I might just sort it out with some kind of directory structure instead. But now I know I don't need to continue looking in the manual at least. ๐
found a way to connect arduino to unity through serial ports. unlocks many interesting elements to my game
indeed it does
i recommend you using structs to transfer larger data instead of sending strings, this allows to group data together rather than line by line or doing weird string tricks
yes, im not doing readline
im working on an ai based game
with cameras and sensors
sounds cool, if you have some progress to post there is #1180170818983051344
would be interested to see
sure
working on a few hybrid projects myself
as of now just managed to connect a joystick
ooh, hybrid projects really add up a lot to a portfolio
thats pretty cool, I recall my first one I did a claw machine with real controls (joystick n buttons) xD
especially ones with real life purposes
i remember doing it with the lego kit
when i was like 10
in unity?
I did it for basically a virtual arcade sim that controls 3d arms in unity, was supposed to be a lan game but nothing came of it cause netcode got annoying with physics lol
Unityโs physics engine isnโt even deterministic on the same device lol
which game engine uses deterministic ? isn't that the side effect of float numbers
ig the trick is to try to mitigate the differences as much as possible? or use server simulated which looks like crap cause all clients are basically kinematic interpolating
Rapier
You can reference a SceneAsset. It is UnityEditor only, so what I typically do is wrap it with the #if UnityEditor conditional and then assign its name to a string OnValidate
never heard of it :\
It is a deterministic physics engine made in rust
But you can also program your own using fixed point math if you want to be simple
Seems like PhysX has pretty similar determinism guarantees as Rapier, which are that if the data is the same, everything is done in the same order, compiled on the same toolchain ..... it's deterministic on the same device.
There probably are some differences, but either way, there are many pitfalls.
Isnโt it a modification deriving from it?
Super interesting, thanks for the insight, I'll look at doing the same!
How can I check if a x euler angle rotation value is between -45 and 45 knowing that -45 reads as 360-45?
subtract 360
float angle = transform.eulerAngles.x;
float normalizedAngle = (angle > 180) ? angle - 360 : angle;
if (normalizedAngle >= -45 && normalizedAngle <= 45)```
Modulo operator
oh you mean like
currentRotationValue - 360 = x
Math.Abs(x) ?
ah, hmm
i think i kinda get it
float normalizedAngle = ((angle + 180) % 360) - 180;
I think
i wonder if modulo is slightly more optimal
but i guess both are pretty close
it's not something that happens too often
use whatever is most legible and make sense to you tbh
the difference are probably so minute they would serve no relevance
yeah i understand the first one better but i'd like to be able to think like the second one
i kinda get it cause i guess with that way it's at most 180 and then you remove 180 and you get a number between -45 and 45
the +180 puts it in a positive range
the modulo is there to wrap it back, then -180 is just to get range -180 / 180
hello does someone know about unity ads legacy for android?
Does it make sense to use Pub/Sub for unity or is it redundant ?
If you want to use that workflow, then itd make sense to implement it. Usually c# events are enough to get by
Yeah I'm working on a coproject but some use that pattern, some use events and it's getting messy
Another weird question.
It's generally preferred to make Singletons for God classes such as GameManagers, AudioManagers etc etc because defining interface for those and use Service Locator would be just an overhead?
that's how i prefer it..
- GameManager
- AudioManager
- UIManager
- sometimes more but always atleast ^
i always use the same variable for the static reference so they all are similar
GameManager.xyz.DoThing() UIManager.xyz.DoThing()
vertx has a good generic singleton on his page that I use: https://unity.huh.how/references/singletons
just have to use Singleton<Class> and tada, ๐ฅณ you have urself a singleton
It's just something that's quick to setup, so every tutorial will use it. I've seen others say that a service locator is good and requires little setup too.
I have an insanely weird bug
Running this code makes the coroutine get stuck during the first yield
Changing Start() to OnEnable() solves the problem
What the heck is going on?
[SerializeField]
private List<RectTransform> _titles;
private void Start()
{
StartCoroutine(AnimTitle());
}
private IEnumerator AnimTitle()
{
foreach (var title in _titles)
{
title.localScale = Vector3.one * 30f;
}
foreach (var title in _titles)
{
var scale = title.DOScale(1f, 0.3f);
scale.onComplete += () => _soundManager.CardPlayedSFX(CardPlayedSFX.Punch);
Debug.Log(title);
yield return new WaitForSeconds(0.5f);
Debug.Log(title);
}
}
by stuck, I mean only one debug.log ever is displayed
Disabling an object cancels its coroutines. So presumably the object gets disabled and OnEnable restarts the coroutine
there is nothing else affecting this object
and it does not get disabled here
also I specifically mean the first time the coroutine runs
if it's called from within Start it stops, if it's called from within OnEnable it doesn't stop
Put this in and see if it prints:
void OnDisable()
{
Debug.Log("Object disabled and coroutines stopped");
}
I mean I know it doesn't because I still see the object enabled inside the hierarchy but I'll test it for sanity's sake
okay what the hell
You can't see it in the hierarchy if it's disabled and enabled during the same frame for example
huh
I didn't know that disables coroutines like that
I guess technically it does get disabled and enabled within the same frame at the beginning
thanks
Why does netcode for gameobjects change lightning of the scene when loading it with NetworkManager.Singleton.SceneManager.LoadScene? The right one is the correct one, and i am using unity 2022 built in rendered netcode for gameobjects v1.10.0
so this doesnt have to do with netcode for gameobjects?
nahh switching scenes in playmode without Lighting settings baked does this
ohhhw ye, this happened before i remember now
alr thanks
Does anyone know why my particle system is visible over my UI elements
this is not a code question
Okay I don't really know where to put this so it is going in here. It is not coding per say but it has to do with editing components of game objects so I hope this is the right place. Essentially, my problem is that I have a 1bit sprite that I'll attach, and I feel like there has to be some automated way to get the polygon collider for it. Especially because it is literally just squares. But I have looked into creating a custom physics shape from the sprite shape and all that but I run into a problem: the bounding box decides to be just a little bit too wide. And so the polygon collider is too big and that is obviously something I would prefer didn't happen
Here are some pictures
this is definitely not a code issue. #๐ผ๏ธโ2d-tools would likely be more appropriate
Ok cool sorry bout that
!code
๐ Large Code Blocks
Use 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 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.
[SerializeField] private AssetReference assetRef;
public bool T;
private void Update()
{
if (T)
{
StartCoroutine(InstantiateCoroutine());
}
}
IEnumerator InstantiateCoroutine()
{
AsyncOperationHandle op = Addressables.InstantiateAsync(assetRef);
yield return op;
}
Here i want to instantiate an object using addressable only once when the bool turns true. but the code instantiates it infinite times, i know cz i am using it in update. But i don't know how to do it correctly to instantiate only once, what to do?
in your coroutine, set T = false;
well, actually i want to use it based on distance proximity, when player is near the target, i want the object to instantiate only once, then what should i do? again i have many objects in the list to activate based of distance proximity
i may be misunderstanding, but this seems like a different thing altogether and i dont see why you wouldnt be able to implement it with your current setup
void Update()
{
float dist = Vector3.Distance(player.transform.position, target.transform.position);
if (dist <= distance)
{
StartCoroutine(InstantiateAssetCoroutine());
//op.Completed += Op_Completed;
}
}
IEnumerator InstantiateAssetCoroutine()
{
AsyncOperationHandle<GameObject> op = Addressables.InstantiateAsync(cubeRef);
yield return op;
}
here is the actual siituation
