#archived-code-general
1 messages · Page 54 of 1
That's what I assumed
Just learned a super interesting C# feature, operator overloading
If you have a custom data class (e.g., a vector3) you can overload something like + for your class, so you can do things like VecA + VecB
public static Vector operator +(Vector v1, Vector v2)
{
return new Vector(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
}```
```cs
Vector v1 = new Vector(1, 2, 3);
Vector v2 = new Vector(4, 5, 6);
Vector sum = v1 + v2; // sum = (5, 7, 9)
So im making a mod for a game I have a mavmesh agent on a game object and it follows the target positions fine until it goes through arch ways where the gap is to small even though the game object it self can go through normally
Idk how to fix
I can't add any nav mesh components to the walls or floors
Any solutions by chance?
Huh that could be useful
Make the navmesh agent smaller?
Depends on your version, its either on the gameobject or in windows > AI > navmesh and then agent as far as I can remember.
By default its 0.5 unity units wide.
I don't have access to scene editor
It's all c#
I will have a look around for the size though
Well, you bake for a specific width, so unless you can rebake the navmesh, I don't see a solution, even if you could change the agents width.
it seems like there are a few "hidden" vector fields given to Transforms. the "forward" vector and the "worldUp" vector being just two listed here. Are there more? what are they and where can I find them? is there a list of them somewhere?
I would suggest you only use it for very commonly used types on which it makes sense to overload some operators, like the Vector struct for example. It's a very confusing feature since the overload is never really explicitly shown in the code
https://docs.unity3d.com/ScriptReference/Transform.html you can just read the Transform docs
Of course, I don’t think it’s a good idea to do something like Child = HumanA + HumanB
.left .backwards .down doesn't exist, its the negative variant of the ones that do. So -forwards = backwards. Its a common questions for people reading this.
seems intuitive
When I run methods like this, will it early return as soon as one returns true or will it combine bool out of all and then return?
return TestDirection(cur, tarX) || TestDirection(tarX, tar) || TestDirection(cur, tarY) ||
TestDirection(tarY, tar);
|| means or, so why would it only return if they were all true?
if you want that, it would be &&
that's now what I asked
I mean
how internally will it get compiled
will it early return and not run another TestDirection is true was already given or will it run them all and only then return result?
early return yes
well the calls are ran linearly
Microsoft says no?
oh
that's bitwise or, not logical or
The conditional logical OR operator || also computes the logical OR of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to true.
| is used against binary comparisons, not bools
So yeah, Slim was right, the logical one returns if the first one is true.
it's boolean operator though
do you know how bitwise operators work?
sir, I do. But this is also used in booleans as you can see
so you can't just say it's only for bit operations
what would be the good approaches for accessing all the assets had been loaded from the remote server?
store all of them into dictionary and get them by the actual file name? or?
tbf he didn't ask for bitwise OR at all 😄
Yeah my bad, I was too fast to link the first one...
Pls help guys
Please don't bump linke this.
Provide more info about your issue and provide the related !code so that we can help.
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
With more info we mean any unexpected behaviour or errors
🤓
"I ask a stupid question and then get triggered when I get called out about it"
how are we supposed to help with "my shit don't work. Help now."
um, actually...🤓 🤓🤓🤓🤓🤓
Oh boy
Surprised you spend energy on such a person at all 😄
it's fun imo, because I like to see how sad they are
💀
@thick heron If you're just going to do silly emojis instead of actually providing details like one would in normal conversation, then refrain from using this discord. It's really not that hard.
#854851968446365696 has a guide to asking questions if you aren't able to formulate one properly.
Also, unless it's a code question, UI and such goes in #📲┃ui-ux.
How would I go about adding an extension method to Gizmos?
I want to add a Gizmos.DrawLine() variation that takes a (Ray ray) as input instead of (Vector3 from, Vector3 to)
I've used extension methods before, just a little lost on how to do this with the whole Gizmos integration
Or is it not possible and I just have to create and use my own class?
I made a script that during run time will be added to my player. That script has a SerializeField for a ScriptableObject I created, I then selected the SO for it in the editor. But then when I run the game and add the script, the SerializeField variable with the ScriptableObject is null. Does anyone knows why and if theres a workaround for this?
On a new run, the script component doesn't know that you changed it in the editor. You could add a reference to the SO and assign that to the script once you add the script to the player.
It's not possible.
How can I add a reference to the SO? like this SomeScriptableObject so = Resources.Load<SomeScriptableObject>("SO/" + someResource); ?
I would just make a serialized field of the SO and drag it in there. You could probably also do it your way, but I'm not sure if your current code is valid.
help i try to change ui text to time but i cant
Help with what? Read the #854851968446365696 on how to ask a question.
Please explain properly on what the issue is instead of just sending "help"
ok
The problem is that you are logging a Single type and it won't properly show like this.
?
You should change it to Debug.Log(timeTake.Value.ToString())
ok but ui
This way it will display the string equivalent which would be what you want
I have no idea what you mean
textMesh.text = timetaken.ToString();
ok
Right now you display the networkVariable type
i learned it today from video (my friend wanted multiplayer for my game)
Well you're close, but you pretty much call ToString on the wrong thing
Hey, I am setting up some animations and I was wondering what happens if I have an objects animator playing an idle animation and then in a timeline play say a talking animation ? Will it return to playing the idle animation at the end of the timeline?
This is regarding this video (not trying to debate whether singletons suck or not):
https://www.youtube.com/watch?v=WLDgtRNK2VE
In this context, what would be the issue with using static classes as the event channels instead of scriptable objects? SOs seem like much more to deal with
In this second devlog, we look at how we employed ScriptableObjects to create a flexible and powerful game architecture for "Chop Chop", the first Unity Open Project.
🔗 Get the demo used in this video on the Github branch:
https://github.com/UnityTechnologies/open-project-1/tree/devlogs/2-scriptable-objects
(compatible with Unity 2020.2b and la...
Hi! When I use ScrollRect and then disable gameobject inside scroll rect which was under scroll in scroll start moment then scroll jumps up. How can I fix it?
Well. SOs are designer friendly. But IMHO most designers should be able to code basics so unless your team is designer heavy then just use a static class 👍 especially if its just you.
hi anyone knows how to teleport clients(players) to position in multiplayer game?
How might I be able to do damage over time?
hey everyone. im trying to make a movement controller. rn, i have ApplyMovement(Vector2 dir, float acceleration)
the problem im running into is making the movement relative to the players forward direction.
Tell whoever has authority over the position of that object to move it somewhere #archived-networking
How do you have the player movement set up? Could you send the script?
accelerationMagnitude = UnitInput().magnitude * maxAccel;
//Mathf.Clamp(acceleration, 0, maxSpeed);
accelerationMagnitude *= Time.deltaTime * surfaceFriction * speedMult;
float veer = accelerationMagnitude*(rb.velocity.x + rb.velocity.y);
float addSpeed = accelerationMagnitude - veer;
//Mathf.Clamp(acceleration, 0, addSpeed);
if(accelerationMagnitude <= 0) accelerationMagnitude *= BrakingDeceleration;
ApplyMovement(UnitInput(), accelerationMagnitude);
}
void ApplyMovement(Vector2 dir, float acceleration){
Vector3 v3 = new(dir.x * acceleration, 0, dir.y * acceleration);
rb.velocity += v3;
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxAccel);
}```
ive tried following a blog post, but i have trouble understanding it
Is it a 3D or 2D gain?
3D
Or should I just use timeline signals
And what controls the movement? Mouse, keyboard, console controller?
keyboard rn
And it's just not moving based on the direction the player is supposed to be facing?
its functional, but only moves along the world axes#
Does the character rotate at all?
ah, it doesnt. the camera controls are part of a child
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(x, 0f, z).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity,turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDirection.normalized * speed * Time.deltaTime);
}
I see, this is how I have my character work when it comes to where the camera's position is.
Thanks
It'll automatically rotate and move in the direction of where the camera is facing.
Why don't you just try it? But after the Timeline stops playing, if it isn't set to hold, the animator should take over again
Do you have a character controller? @mossy minnow?
Note that mine is for a third person camera
Not for a first person
If yours is a third person you should be able to use this.
oh yeah this is for first-person
Well, Vector3.forward controls the direction of where the GameObject is facing.
My stuff here should work... I think for what you have.
Since I don't think it explicitly says that it is only for third person, jsut the video or where I grabbed was.
Just how I configured it might be different because I use cinemachine.
You could have the camera rotate on the axis of the mouse, but lock the player's rotation to only move about the Y
Just reference the camera's transform when doing the rotation.
transform.rotation = Quaternion.Euler(0f, angle, 0f);
This control's the player's rotation.
Because your character doesn't rotate, or I assume does not rotate because there's nothing saying it, it is moving "correctly"
Your inputs are correct, to me at least, but without the player rotating based on the camera's rotation, it doesn't work.
Also
Be sure the camera is facing where the camera is facing.
Otherwise it you basically have eyes at the back of your head, literally.
hey guys, i am using HDRP and i am creating a room geometry procedurally at runtime. i'd like to have a bit more of a realistic lighting. currently everything that is not directly lit but the sun is super grey. some indirect light would be amazing. i don't know much about HDRP and lighting in unity in general but from what i think i picked up is that the whole procedural thing is a bit tricky since most of the lighting magic is prebaked. does anyone have any tips or resources for me?
Did you checkout realtime global illumination and other topics, I am sure there are some hdrp tutorials about lighting from Unity or 3rd party creators?
yeah i did check quite a few tutorials on that. but no one seems to be creating their geometry at runtime..
So this is my file heirarchy
Lets say I want to grab a reference to ChoppableData asset inside the Script at runtime.
I also want to do this through code, without having to manually connect anything in the Inspector.
Is there any way to do this without using the Resource folder?
yeah. Realtime GI is the way to go.
There are a few asset store solutions AFAIK.
What you want is basically ray tracing.
OR compose and light your scene with realtime lights only
you could use Resources folder to get that or StreamingAssets or Addressables
I will look into StreamingAssets and addressables
yeah i have raytracing enabled already. but still things a looking strange
Guess you gotta up the shadow quality and also the resolution
#archived-hdrp might be agood place to get further into
It's not really about the shadows but the objects not being lit directly appearing all grey
Like there is just light and no light
ok, thanks i'll take it there
Am guessing its probably your skybox doing this. 🤔 But not an expert. Instead of #archived-hdrp try #archived-lighting 👍
Wasn't in front of the project. -_-. Just trying to preplan how I should set things up
but thx for the information
why does my function just decide to end early
Hard to say, do you go into the catch?
Probably accessing Unity Engine objects in a background thread
https://docs.unity.com/lobby/en/manual/create-a-lobby
The example says to do it otherwise, why are you doing it this way?
CreateLobbyOptions options = new CreateLobbyOptions();
options.Data = new Dictionary<string, DataObject>()
{
{
"ExamplePublicLobbyData", new DataObject(
visibility: DataObject.VisibilityOptions.Public, // Visible publicly.
value: "ExamplePublicLobbyData")
},
};
i saw a tutorial that did it that way
I would follow the manual. But it's still strange that you don't see any error in your IDE.
Can anyone help me understand how one of my FixedUpdate() functions is running before a Awake(), should be impossible?
Its impossible, in the grey boxes the order can change afaik, but between the grey boxes it's not able to.
when i try to acces the joinCode data unity tells me that JoinCodeData doesnt exist in the current context
I know it is supposed to be, yet i am getting a null error from a fixed update, before my awake funtion is called, i am debug logging it
Can you show your code?
How to move array items up?
so I remove an item from index 4, how to shift 5 and 6 up?
also if I remove a few items from different indexes, how to move everything up to fill the empty spaces?
If you don't want to support empty spaces, why not just use a list? Then it would do the things you describe automatically.
The thing is I'm using an inventory system by asset store @main shuttle
so I can only make an extension of it to overcome this
and the whole system uses array not list
I am getting a null error in the second code piece, before any dbeug output from the first one.
If i move it to onEnable isntead it works
I'm not sure, you seem to be doing some overriding stuff, the left part seems to be inherriting from something, you FindAnyObjectByType that could cause issues and I'm not sure when both scripts are called. If it works in OnEnable, just keep it there.
alright so i've been slowly losing my sanity trying to do the single simplest thing on earth which is to literally just change the parent of a gun to an empty gameobject and reset the gun's localposition (with code)
but no matter what i try, it's just not working
it always keeps the world position
no, no other scripts are modifying the gun's transform or anything like that
Not sure then, normally it's pushing and popping, but C# doesn't seem to support that in arrays. You could of course program it yourself.
ok thank you
How do you use !code again lmao can't figure it out 
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
My smol brain can't understand
myGun.parent = newParent;
myGun.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);```
Hello, I have a problem since I can not access the play mode by an error, someone could help me thanks. I have come to wait more than 30 minutes and it has not worked for me, any solution?
- try restarting Unity
- if the problem persists, perhaps you have written an infinite loop in your code, which is freezing the application?
This is the code
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
didn't work
it works. if it's not working you have some other external issue going on
you have to share more details if you want more help
you are no doubt missing something
how do i read the data now ?
I don't understand the question, what data? options.Data is the dictionary you put in.
If you want the lobby data, go to the next part of the manual
i added the join code to that data now i need to read the join code
But you already have a variable holding the join code 🤔
I'm so confused...
the other person who joins the lobby needs to read it so they can connect to the same relay
its for multiplayer
I was trying a new approach for movement code, but the code below is running framerate-dependent meaning the movement speed varies depending on the fps. It... shouldn't be like that, right? I'm multiplying by delta time in the MoveTowards function's maxDelta parameter and am multiplying the overall movement amount at the end by delta time as well.
I've done this kind of thing a thousand times before in dozens of projects and it feels like I'm missing something here. I am incredibly sleep deprived right now, so maybe that's it and I missed something. Any help would be appreciated
vel.x = Mathf.MoveTowards(vel.x,strafeSpeed * Input.GetAxis("Horizontal"),accelStrafe * Time.deltaTime);
vel.z = Mathf.MoveTowards(vel.z,speed,accel * Time.deltaTime);
transform.position += vel * Time.deltaTime;
we have the person who creates the lobby they add the join code for the relay to the lobby so other people who join the same lobby can get said code for the relay and when both are conected to the same relay they should in thorie be able to play together using unity netcode
I don't know then. Maybe ask in #archived-unity-gaming-services since it's Lobby.
I would assume the manual would explain this
this looks... ok I believe... Can you share more code?
Yeah it's so strange. I've removed every single thing in the scene except for this one script, a player object, and a flat "track" to see the movement + a line to print the current speed, and it's still happening. All I have to do is maximize/unmaximize the game tab to see the effect of the framerate dependence.
The script is as simple as it gets -
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
public float strafeSpeed;
public float accel;
public float accelStrafe;
Vector3 vel;
void Update()
{
vel.x = Mathf.MoveTowards(vel.x,strafeSpeed * Input.GetAxis("Horizontal"),accelStrafe * Time.deltaTime);
vel.z = Mathf.MoveTowards(vel.z,speed,accel * Time.deltaTime);
transform.position += vel * Time.deltaTime;
// Print speed
print((vel * Time.deltaTime).z);
}
}
I just thought using MoveTowards would be nice to simplify acceleration/deceleration operations, and it works perfectly atm with just 3 lines of code except for the FPS dependence...
vel * Time.deltaTime; and speed,accel * Time.deltaTime accelStrafe * Time.deltaTime
You Time.deltaTime the vel twice? 🤔 Shouldn't be the problem in my head, but it's still weird for me.
does anyone know how to set up mediapipe for unity by any chance? i need some help
If key pressed and this function run, it doesnt work?
Any chance it's just a perception thing and you're interpreting a movement of more pixels on screen as "faster" in game world, when it's actually not?
It should be correct afaik. MoveTowards linearly moves one float towards another at a fixed rate (my acceleration variables). So need to multiply the acceleration value by delta time in my MoveTowards calls, since I'm doing it every frame. Then, at the end, I'm going to actually move the transform by the resulting velocity I have, so I also need to multiply by delta time there as well. Am I wrong about it? 🤔
Or it's the actual camera that's lagging, depending on how you set that one up.
I think the code is OK. Though since you're doing your own acceleration I would probably use GetAxisRaw instead of GetAxis
Check the bottom left of the screen if you can see it. That's the print call from my previous message printing the speed we're moving at. It changes when I go from a small game view to the maximized game view, and it's pretty clearly changing speed to your eye as well. Idk I'm wondering if I'm going crazy or don't understand how something works now...
Lets say you want to go 1 to the right, and 1 forward every second, you Time.deltaTime both, and get 0.02, 0,02 as a vel and then you Time.deltaTime that again. I think it's wrong, but it should just be a lot smaller then the actual value, it still shouldn't stutter.
that's not printing the speed you're moving at. it's printing the distance you move in one frame
it's normal and expected for that to be different, since the frame durations are different.
what you should print is vel itself
or vel.magnitude
or vel.z
get some rest
thank you and sorry for being super dumb LOL
yeah you're 1000% right it's working fine
I think the editor frame skipping or whatever was making it look like it was moving faster in the smaller window, and since I was printing the speed the wrong way it was "confirming" my theory
never felt more mortified in my life rn
If this is the worst, you've lived a blessed life.
Sleep is good, working while sleep deprived is bad. Nice lesson of today.
my rigidbody based player character has different jump heights on different pcs, i'm guessing it's because of the different frame rates, for jumping im setting the players y velocity as the needed jump force
this is why you take inputs from fixedupdate and consume them elsewhere
or better yet: use events
well i tried putting OnButtonDown in fixedupdate but then it just ignored the input most of the time
it's a good idea to assume when something doesn't work that it's your misunderstanding rather than the engine not working correctly
and i just realized it may be an issue of drag changing later
I mean, the reality is that you should never use physics values that change
unless there's a direct reason, there's no sense in making your jump force anything other than an int or float
SerializeField it, and change it from the inspector
for more advanced physics I use things like AnimationCurves, or algebraic functions
oh the jumpForce doesnt change, drag changes though
i have a function that deletes an instantiated prefab if the "is_clicked" bool is true (the bool is in another script inside the prefab) but it only works for one object in scene, if i have more then one an error occurs how do i fix it? here's the full script : https://paste.ofcode.org/n3w5VdJ2hgZjANv2VvR4Ep
A: How are you calling the delete method
B: what is in the "spawned" variable
edit: nevermind did not see the paste of full script. One sec
Yeah. So.
Your spawned variable will only ever contain the latest added workout.
I guess what you want to do is on custoum_workout_clicked() you should assingn whatever was clicked as your "spawned" variable. (and rename it to "selected" probably)
that worked, thanks
Anyone know what the best practice is for a complex inventory system using scriptable objects in regards to item stacking? In my list of items would I add another instance of the item scriptable object for each? Or would I store an amount somewhere, for example a static count property on the scriptable object? I am new to inventory systems, so please feel free to correct me if I have anything wrong here
Anyone who have experience making Controllers using ScriptableObjects? I played around with it a bit and seems like more problem than benefit
Why make it a scriptable object in the first place?
And yes you should just keep track of the count in a variable. No need to create instances. But why make it a static? Can't more people own a stack of an item?
Yeah. Most likely it is. What are you even using them for? By "controller" I assume you mean translation of input into commands for a character right?
Not so much the translation of input, more the actual act of moving objects and performing basic actions.
Jeez. Why make it a scriptable object? What led you to that?
The items themselves are scriptable objects. I may have worded my original question in a confusing way, my bad. Your reply answered my question though, and I have a pretty good idea of how to move forward now. Thank you
The entire unity component system just seems very clunky to me haha
I need to interpolate between points to make a curve, and sample more points to smoth the lines. (In 3d)
I planned on using splines, with tangent control points, but I cant find any tool for unity to create the splines. I found a package, but it seems to be discontinued
this is what I want to do
what can I use?
actually I think its a bezier curve
not a spline
yes its a bezier
Unity has an official spline package:
https://docs.unity3d.com/Packages/com.unity.splines@2.1/manual/index.html
its not in the package editor
seems to be discontinued or smth
it's not discontinued
it's brand new
you have to add it by name
com.unity.splines
^
ty
oh
I was looking in the spline class itself
thanks
any way to sample between two knots tho?
like, 0.5 of the way between knot 1 and knot 2
.getCurve() seems to get the individual beziers, but again I cant find the method to sample it
im sorry, im usually not this bad at moving through docs and code not my own
this package isn't organized in the most user friendly way I'll grant you that
I only happen to have a little experience with it
I've found that the API is pretty thorough, if complicated.
yea
that should be everything I need, hopefully
Is it possible to convert an Mp3 into a Wav at runtime?
I'm trying to integrate amazon Polly to get text-to-speech but I can't directly receive a WAV, so far I request,get and save the speech as mp3, now I need to convert it before playing it through the audiosource
Seems that unity can't directly do that, I found some suggestions redirecting to something called NAudio but can't find the dll anywhere...
how can i make a football ball dribble system with blend trees
probably a nuget package
is there a way to destroy game objects from a list? I am trying to figure how how to make it so the player can instantiate objects, but only a certain amount of them. The instantiation is going fine, but the destruction is not.
Destroy will destroy whatever object you pass to it.
It doesn't matter if the object is in a list or not
note that if you destroy an object in your list, you should probably also remove it from the list, otherwise you have a reference to a destroyed object in there.
when i try that- i get the error “Destroying assets is not permitted to avoid data loss”
Sounds like you're trying to destroy a prefab
don't do that
only destroy instances in the scene
ah yes- how do i destroy the copy
is your question "how do I get a reference to the copy"?
Instantiate returns such a reference
var theCopy = Instantiate(thePrefab);```
Hello. What is the best way for me to switch scenes after an animation has played 5 times?
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
I am aware of the scene manager. However I need the scene to change after an Animation has played 5 times.
So count, and then change scene
Or is the question actually about how to see if an animation is done playing?
that, and how to count it.
You could just add an animation event that counts up at the end
+1 to a int?
int equals 5 perform the action
Didn't think about that, its been a long time since I've needed animation events. I will try it out!
It all depends on your setup. You could also start a coroutine that starts the animation and waits for it to finish and then +1. Many ways to Rome on this one.
I made an animation where the player digs with a shovel. The whole idea is that once the player shovels 5 or so times, the scene will transition to where the player has a shelter.
This is a sequel to a game I made a year ago where a militia soldier is stranded in the Swiss mountains and supposedly froze to death
sounds like a cutscene. could just do it all in timeline with a signal at the end to switch scenes
or you saying the player has control over the individual shovellings?
the player holds the Space key to start shoveling
like this
and the shelter would just be a simple hole in the wall of snow, and then a emergency blanket on the door to keep heat in while keeping cold out, and maybe some candles or something
I have been stuck on a weird null error for a while now.
Essentially the jump function crashes on null erros if called as a delegate, saying that my Player object (this) has been destroyed, but it works fine if called manually through the script...
sounds like you subscribed it to a delegate somewhere and never unsubscribed when your player object was destroyed
The thing is my Player object is not destroyed, i am 200% sure. Any object i try to log in the function through the delegate is null, while i can log them from anywhere else after and they are not. i put OnDestroy logs on to check to make sure. I fixed the problem but it still makes no sense to me. If i assign the delegate function through another class, with a reference to the class containing the functions, it doesnt work
Your player will be destroyed if you load a new scene, for example
Is there a way to convert a ScriptableObject into a struct?
this question doesn't make sense
Asking about your attempted solution rather than your actual problem
No new scene loaded, it is anything i try and log through the delegate function, if assigned through another class.
you'd have to show your code, scene setup, and error message etc.
Tell us what you're actually trying to do
I need to store weapon stats as a struct so that they can be synchronized in multiplayer, but I would like to also store them as a ScriptableObject and then read them into that struct, so that they dont get deleted if for example I remove the Component holding the struct from my gun game object
Make the struct that contains the data.
Make a ScriptableObject containing such a struct
[Serializable]
public struct MyData {
// stuff
}
public class MySO : ScriptableObject {
public MyData data;
}```
okay, thanks, I didnt think about that
Is there a cleaner way to write a command system like this?
https://pastebin.com/MpMUjdry
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.
yes
make a tree structure of commands
how would you go about doing that/ could you link me to a reference on how to do it or something?
quick and dirty example is something like:
public class Command {
public Dictionary<string, Command> childCommands;
public Func<CommandResponse> execution;
}```
Then you build it like:
```cs
Dictionary<string, Command> tree = new() {
{ "debug" : new {
childCommands = new () {
"devsight": new {
childCommands = new() {
"disable" : new { execution = () => return new CommandResponse("Devsight Disabled.");}
"enable" : new { execution = () => return new CommandResponse("Devsight Enabled.");
}
}
}
}```
Then just do a loop over your arguments list and traverse down the tree until you find the one to execute
interesting approach. I will definitely look into that, thanks.
I'm trying to Tile.SetColor but it seems like Tiles have the LockColor flag enabled by default, preventing that. I disable it in the code through a mask, but it doesn't kick in until I reload, and only lasts so long as I don't quit Unity. How can I set LockColor to false once and for all?
E: fixed, solution was to use RemoveTileFlags
is it possible for a script to access the properties and attributes of a child object of the object it is attached to
Hello, how can I transform a cubemap shape from Cube to Sphere?
say, would someone with rigidbody collision forces experience know if/what to do if I want to find the force being exerted on another object? like, if I want to find the velocity being imparted on a rigidbody from the collision of the two.
Reason being I want to be able to include that in jump forces to impart some of that momentum into a jump, but I need to be able to set the jump force directly because I don't want to factor in current player y velocity since I'm changing gravity directions
https://docs.unity3d.com/ScriptReference/GameObject.html
Check out the public methods
does any1 know how i can change the input this object gets with a different one in my assets?
Are they all inheriting from card?
Rather, a different variation of card
uh sorry im bad at explaining things but pretty much my end goal is whenever it loads the upgrade screen i want it to set this value to a random object from a list
i have like different presets for it
i just wanna know how to change the object to something random from my assets folder
random.Range ?
Are there particular assets you're wanting to switch to?
Right, so you have a prefab called Card, but you're setting the SO initially on the inspector. If you want different values on this prefab, you'll have to pass that information in when you init the prefab.
im fine with doing the random part
I think you want to put those prefabs in a list, and pick one at random when you instantiate the prefab
its just the swapping it to an alr created present
so would i make the list by adding each card to the script
and swapping
cuz i thought of doing it
[SerializeField] Card[] cards;
public Card card;```
yeah
^
Don't use a list just use a array. Lists can't be modified
okok lemme try that thanks guys
What do you mean by that?
It's the opposite
Either should be fine.
Yeah, lists is better imo just cos if you go through it you won't have a null at some point
But probably irrelevant for that problem
sorry for another question but how would I change this object with one from the list
Drag it
i meant with code
card = cards[something]
to better clarify my question: I'm attempting to get a vector as a result of a collision between two rigidbodies. I know they generate contact points, and I'm looking at the documentation on that, but I'm not sure what returns information I'm looking for.
It's not the velocity of the object, it's the velocity projected from the surface normal of the contact point that I'm looking for
I've found things like ContactPoint2D.normalImpulse, but that's a result of the momentum of objects colliding I believe, and not a static force (meaning if I ram one object into another this number fluctuates based on the initially collision speed) and I'm looking for a force exerted by the object simply based on that point's movement vector,
head hurts
card = cards[random.Range(0, cards.Length)] should give you a random prefab out of those you put in the list
Sorry I did get it backwards Lists are what you should be using.
i take in the card prefabs here
I actually don't know why, does that have to do with memory allocation?
then i want to change this object to one from the list
im just unsure of the code and cant find anything
I tried firstCard.Card = card;
after i set card
You might have to put [serializefield] in front of each field
So you can fill it in editor
No lists are just much better in the end of things to do a lot more. If he makes a mistake in using arrays then he will be to recode all over. They do the same but Arrays hold a fixed number of items and can not be changed via code to be manipulated.
That's what I don't get, Can't you reallocate them in code? I actually never tried
Honestly my experience with Arrays have been only once and I had to rewrite my code because i needed to change and sort etc which arrays can not do.
They have their use for specific problems tho, I use them for equipments or spells since the amount never changes and it's easier to make an empty slot
If "card" is of type Card, then "firstCard" should be of the same type, if your goal is to set the card to another specific card type
im really bad at explaining what im trying to do
In my game i had to sort a certain plant price and health of the plant by the int as i collected them and I maybe spent 2/3 days trying to make it work but never could until i was told i was using a array and arrays can't do any of what i wanted to do. So from then on I only use lists because in my mind lists are almost the same with arrays just no cap unless you program it cap like remove 1 off when it gets to a certain count
Probably cos you don't understand it well enough, but it's ok. I don't know what to tell you without directly giving you the solution, which won't make you understand :p
Well, whats the issue that your running into currently? And whats the outcome, in a perfect-world scenario that your looking for?
im making it so when you press or a button (later on opening chests) it loads 3 upgrade cards that are random to player. Everything is done but swapping 1 object which is this
my code takes in the upgrade cards objects here
i just need a way to say hey firstcard.card = card;
you should be using an array or List
not three variables
this is probably rlly simple so im sending it here (ik i switched channels thats cause im not rlly a beginner but im not like the best)
i have these sprites inside my player prefab, which can be changed in the avatar editor. when you hit save, the player becomes a "dont destroy on load" but once you go back to the avatar scene theres another player still there, how do i delete the original player and swap its place with the edited one?
cards are the list of the different upgrades
the firstCard secondCard etc are the display
which change once their object card changes
card probably doesn't need to be public or serialized. You don't want to see it in editor, since you'll only use it through code
Use a scriptable object and load that when you go back and forth between.
Or just store the data about the player somewhere and have the actual player object just read that data at scene load
Then make a list/array of cards that you do serialize, and fill it by dragging your prefabs in it in the editor
rather than the player itself being DDOL
bc i got like half of this but now bc its not in the actual scene the editor cant find the sprites
ima screen record an explanation and send it if thats alright
this will be a lot easier to do with an array instead of three variables. something like:
for (int i = 0; i < cardDisplays.Length; i++) {
cardDisplays[i].Show(GetRandomCard(cardsList));
}```
I have a question regarding rotations if anyone is able to help. I'm trying to rotate a cube as I move it but the rotation is getting messed up for different configurations. It works when moving in only the x direction, or only the z direction, but when I use both the y rotation starts changing, cant figure it out, my code should be simple: https://paste.ofcode.org/jq7muVBw4nFgVsTv6ZnjgA
what's the desired result?
What its doing is when you load a scene its bringing back the old sprite as what its programmed todo when you go to that screen if u don't want a new character just save the character as a scriptable object and it will always stay there or you could just have each item as a item code and write it to a Json file and than load that file to add all the prefabs.
here if sm1 can watch that and kinda understand what im trying to do
bc idk how else to explain it
I know what ur trying to do but don't think ur understanding us.
You want to create a box that you open and when it opens 3 cards will appear but you want the cards to be random from the list of cards you have already made. Correct?
The desired result is that the cube will be oriented based on direction of movement. It's a die, so if I move it right, if the number 1 is on top, it is rotated so now one is pointed right, move right again it is on the bottom etc. This works when the rotation of either x or z is zero, can move it any times in z direction and it rotates properly, or any direction x and its great, but if I move it one time in the x, and one time in the z, the rotation no longer works properly, instead of rotating the number on top will stay the same and rotate around the y axis
Don't you just want this then?
https://paste.ofcode.org/SJwJyLZZAab7FJiJ8HXdmX
Why are you doing like... additive rotations?
yes i have all of that done but swapping the object to a new card
Should I use WaitForSecondsRealTime when dealing with audio?
Put a button in and when you press it than you will random roll another card ?
Oh wait I see what you're saying, it's a die like "rolling" around
exactly
wdym by the y rotation starts changing? Is the die actually rotating improperly? Or are you just getting upset about the numbers you see in the inspector?
Note that euler angles are not really reliable or useful since there are infinitely many equivalent euler rotations for a given orientation
Why not Mathf.Clamp the values on x, y & z?
The axis of rotation should change according to previous rolls, is that what you mean?
in my code i call on first card which is the "Card" in the hierarchy and it takes an input "Card" as you can see is currently magic damage. Im trying to change MagicDamage to a different card with code
By pressing a button?
do u see how in the Card Display script it takes in a card
yes i alr have the button function done
i even
call first card
OKOK wait
lemme show an example bc i do it using textmeshpro
You got to put it in a Method and make it public
here
do u see how i take in nameText
and change the value
im trying to do that
but with a different object thats not textmeshpro
if u watch the full video
i show everyhting
the button alr works
the list alr works
its just setting the current card to a different one
like the object
I think I understand where your problem comes from actually. As your object rotates, the axis of rotation moves with it.
Do the same thing with random range ? you can put ints in for numbers and make ints stand for strings or objects etc
You're still doing the same thing, like rotate again in the x axis, when the x axis is not the same one. Doe s that makes sense?
It's the same one for the die, but not from your perspective
The first two directions I move die its fine, rotation of x and z work perfectly, but when I move once in the z direction then move to the x it breaks, I don't mind changing from euler angles, but using other rotation methods weren't working, this was as close as I could get what I wanted
ahhh video didnt post correctly sorry
I think the easiest way to solve it is to deal with it in a absolute way, store the value of each rotation to the corresponding face of the die, and change rotation from the last rotation (that you stored) to the new one
Dunno if all I'm saying makes sense ^^
See when the die is on 4 and doesn't change? That's because it's rotating around that axis
It sounds like your looking for a GetComponent on your object that has CardDisplay, when you pick your random value
You can actually see the other faces changing
yes
i found another way to do it
Yes, I understand its rotating around the Y-axis after moving once then in a different direction after, I'm just seeing how I can fix it
Is that other method public?
public void setCard(Card input)
{
card = input;
}
this should be fine right
its just in a different script
Make an array of cards, drag every available card into it and then randomly select a card in code.
the script im trying to call a method from is on this game object
Maybe deduce the new axises of rotation at each turn
and i call it by using firstCard.setCard(card);
What type is firstCard?
i have firstCard as GameObject
this is first card
why wont this work- i want it to make its parent anything with the tag "List" on awake but it stays on DDOL
A GameObject wont have access to your public function, youll have to access it with either GetComponent, or make your firstCard the same type as the class that has your public function your trying to access
can u show me an example of how I would use GetComponent it kinda confuses me
Rigidbody2D.GetPointVelocity (declaration: (public Vector2 GetPointVelocity(Vector2 point)) with "point" being the global space point to calc velocity for)
I already am getting a collection of contact points when colliding with objects to do ground check stuff... If I want to examine those contacts and then getpointvelocity information from them, does anyone know what I should do?
What doesn't work? The stuff before and after but are not related.
For example:
void SomeFunc()
{
someObj.GetComponent<RigidBody>().velocity = Vector3.one;
}
someObj being a GameObject, and Rigidbody being the class I wanna access velocity from
Just have it referenced as the correct type to begin with.
i want it to like keep the object when transitioning the scene and then i want it to parent it to the object with the tag "List" right after
if player doesn't exist
set instance
set exit
set parent
parent set DDOL
else
destroy gameObject```The parent has to be a DDOL object as well.
had to add some stuff to this and i finally got it working
How do I serialize a field in a component such that said field is clamped between the values of 0.0 and 100.0 and utilizes a visible slider?
[Range(0, 100)]
Ooh... 🤔
Is there any other way? cant really export that as a package for the asset store
Thanks man. 😄
Hey, I'm trying to change music on the next beat after an event.
Does that look right? It's hard for me to check, I suck at rhythm. (bpm is 100)
float timeToWait = (float)(AudioSettings.dspTime - MusicManager.instance.startBossMusicTime) % (60f / 100f);
I guess there's missing info, that's the time I want to wait between the event and the next beat
MusicManager.instance.startBossMusicTime is the time when the music was first started
break it down so the math is easier:
float bpm = 100;
float secondsPerMinute = 60;
float beatInterval = secondsPerMinute / bpm;
float beatNumberOfEvent = 10; // you decide which beat number the event happens on. 0th beat is the start of the song.
float eventTime = beatNumberOfEvent * beatInterval;```
then I suppose:
float timeRemainingUntilEvent = eventTime- AudioSettings.dspTime;``` assuming dspTime is the current playback time of the song
the number of beat before the switch is unknown, it's turned based RPG, the music changes at the end of the fight
what is "the switch"
Switch in song
Are you saying you want to know what time the next beat is, given the current time?
Or I guess in audio
Basically yeah
int mostRecentBeat = Mathf.FloorToInt(currentSongTime / beatInterval);
int nextBeat = mostRecentBeat + 1;
float nextBeatTime = nextBeat * beatInterval;```
I agree with what you said tho, I think I sacrifice readability for number of code lines too often ^^
This is how I do all my complex calculations
I like it to be so stupid simple a toddler can read it
not literally I guess but
Understandable, also increases adaptability
Putting in raw numbers is meh overall ^^
Alright, thanks a lot for the advice 🙂
Is there a way I can make certain serialized elements in a component enabled/disabled pending the value of a certain boolean?
Download NaughtyAttributes
It will make your life easier
Github
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickToMove : MonoBehaviour
{
[SerializeField]
[Range(2, 12)] //slider
//MAKE SURE U TURN OFF GRAVITY OR IT WONT WORK
private float speed = 4f;
public Animator animator;
private Vector3 targetPosition;
private bool isMoving = false;
void Update()
{
if (Input.GetMouseButton(0))
{
SetTargetPosition();
}
if (isMoving)
{
Move();
}
}
void SetTargetPosition()
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.z = transform.position.z;
isMoving = true;
}
void Move()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition)
{
isMoving = false;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
//Check for a match with the specific tag on any GameObject that collides with your GameObject
if (collision.gameObject.tag == "StopPLR")
{
//If the GameObject has the same tag as specified, output this message in the console
speed = 0f;
}
if (collision.gameObject.tag == "StartPLR")
{
//If the GameObject has the same tag as specified, output this message in the console
speed = 4f;
}
}
}
this is my characters walking script, a click to walk type thing, and i have a question, how come the animations playing disables the player from being able to move
Sounds like your Animator is animation the position of your character's root object
Either make it only animate a child object or turn on Root motion
oh ok tysm!!
i did root motion and now its just glitching from side to side
I recommend making your sprite or model as a child object and animating its localPosition
how do i make it a child object
putting in under a parent object?
hey so im trying to do animations for hurt and death how would i go about taking damage and dying i cant figure it out any ideas?
Dont crosspost. Also #archived-game-design
hey is there a generally accepted standard character for separating strings for splitting?
It all depends on what youre trying to split. No standard.
my script wont enable my walk anim
shouldnt this work
animator.SetBool("Walking", true);```
nvm i did it!!
Card names. I'm currently second-guessing what character I'll guaranteed never use.
\n?
Semicolon is a common one too
Why are you creating the string you have to split though? Why not just store it in structured data from the get-go?
I'm saving a deck recipe with playerprefs. probably not what I should be doing but it's how I know how to do it and it's fine if it's temporary.
how do you declare a trigger thats in your animator to you player script lmao
i might be having a stroke or not rn
Is there a way to create projection matrix for a given field of view, without creating a camera?
why will my scenes not switch in a build 🗿
ASCII Character code 7... 😛
Commas, Tabs, Pipes... eg. CSV.
Found out that the new System.Text.Json isn't available in unity due to it being framework/net standard but it might have access to something gross that i like to use for delimiter parsing
using Microsoft.VisualBasic.FileIO;
public static IEnumerable<string> SplitCSV(this string source)
{
using (
var parser = new TextFieldParser(new StringReader(source))
{
HasFieldsEnclosedInQuotes = true,
TextFieldType = FieldType.Delimited,
Delimiters = new[] {","},
TrimWhiteSpace = true
})
{
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
if (fields == null || !fields.Any())
continue;
foreach (var field in fields)
yield return field;
}
parser.Close();
}
}```
this textfieldparser is super slow though
Comma is likely to appear in a card title somehow eventually. (this is a mtg-type game). Pipes work though I'm looking for something between common enough to not have to look up the ascii code when I constantly forget it and something I won't use in perpetuity. For now underscore is good enough.
and I was adding walljumps
I highly doubt your card names will contain a tab /t
tab delimeted files are also very very common
if I spam jump while on a wall
instead of walljumping
sometimes it will do a regular jump
this is because my ground check triggers with the wall
even though it shouldn't
my theory is that the player goes through the wall for a split second because its moving too fast
so the ground check gets triggered
i know that the groundcheck is triggered by the wall, and thats what im basing my guess off of
it sounds like your groundcheck is overshooting your character horizontally.
i thought it might
but its not
i think
here ill send a screenshot
oop
no you are right
LOL
look at this
wait nevermind
it dosent overshoot
i have a rounded hitbox
sorry i though the inner square was my collider for a second
mind if you share a screenshot of your rigidbody settings?
sure
this bug happens even without interpolation
i have continuous col detection, which I'm pretty sure is as good as it gets
if you want ill share my code as well
yeah i was seeing if you had that on
ill remove all the comments of my code and send it so it is easy to read
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
here you go
i removed all comments
im gonna try using a boxy hitbox
and see if that changes anything
actually i figured it out
so im pretty sure my ground check needs to be behind the inner squre of my rounded hitbox
because if i decrease the edge radius back to boxy
now the ground chekc overshoots
is it bad to have the ground check be too tiny though?
Has anyone figured out a good way to have an inline editor for a scriptable object? (I have Odin but InlineEditor does nothing)
ok this bug is rare usually so i may be wrong
you’re sure the issue is with the ground detecting the wall right?
yes
because i had a debug log
that sent out what object the ground check was colidinig with
and when the bug happened it sent out one saying it collided with the wall
so im positive that its that
ok, you could try moving your ground check code into FixedUpdate(), or try shrinking the horizontal size of the ground check
is ti bad if its too small though?
like lets say the player is making a big jump
and lands like right on the edge
i mean once they fully get on the platform the ground chekc will trigger
but like for that little bit of time it isn't
is that ok?
i use ontriggerenter/exit events for my ground check
it might not be if it’s extremely noticeable. but try seeing if moving the ground check to FixedUpdate fixes it
i dont call groundcheck in fixed update
here lemme send a snippet of code
this is on my groundcheck trigger object
sorry for the screenshot its just a rly small amount of code
so i think these events already run in fixed update
if im not mistaken
i think the bug is fixed though
i will report back if it isn't
thanks!
photon seems rlly outdated for my unity, what do i do:(
What do you mean by that? Photon is also the name of the collection of their products, but I assume your referring to PUN 2 (Photon Unity Networking v2), or PUN Classic? Or a different product like Photon Fusion or Bolt?
Wdym by outdated though?
im trying to get my gun to shoot in the direction of my mouse
it only goes in one direction when I click the mouse
im pretty sure it is having a problem finding the location of the mouse
how are you updating the aim in correlation to the mouse?
are you detecting mouse position each tick and moving/rotating?
you're seting shoot direction to 4 different values
the input position, you zero the Z, then you set it to a camera position based on the shoot direction
im not really sure what that is all doing
i assume Z is the same direction as your flat plane
eg. shoot along the plane
what is transform.position?
what happens if you take out those shootDirection things and just have one?
see what different effects that gives?
eg. just have that first one and remove the other 3 (comment them)
id have the first two if the mouse position gives you a strange vertical value
the bullets act different
I got it to update
the direction I didnt know how to check to see if it was working
but now it updates the values in unity when I move my cursor on screen
but when I click it just comes out the same side
and goes in 1 direction anyway
hmm it only updates 2 values
Does the bullets fire from the gun end or just appear in middle of screen?
from the end of the cube
there is a cube floating above my blue ball
i was trying to keep it simple for learning
looks like this
I just want to create objects on what ever side I click really
Why don't you move the cube to the front of the ball and have the bullets fire from the cubes location and move the character with your mouse movement
finger is same as a mouse input
yes
the ball is suppose to roll around and the top part should shoot in the direction
its like a tank
the ball moves already
have the box fixed on its axis so it wont move with the ball?
i just have the cube locked at the moment because the ball rolls with the sphere so it keeps hitting the floor every time I roll
i mean roll
im just messing around for the sake of practice
but its a cool mechanic that i want to learn
So works now?
no
Whats not working then
Like i said move the box in front of the ball and have the bullets fire from the cubes location or a game object
thats what a clip looks like
thats not what I want to do though hah xD
hmm
what if I can make a ring around the sphere
U want it to fire from where the ball is facing?
have a ring around ur character and have the cube rotate to where mouse is
Has anyone here ever made an extension method for MonoBehaviour? This function compiles itself, but I can't use it anywhere
public static bool GetComponent<T>(this MonoBehaviour behaviour, out T component) where T : MonoBehaviour
{
component = behaviour.GetComponent<T>();
return component != null;
}
like or moon orbiting the earth but just where the mouse/finger is
https://www.youtube.com/watch?v=rKGsELBgpQY best tutorial for rotations.
ty
does anyone know how to make a particles in a particle system go in specific rotations based on the direction they are going? I'm trying to make my attack look better
you can turn down random and change the orientation in the inspector for the particle system and change the shape to a box not a cone for more control.
So I’ve been looking though System.IO special files/folders
I have found that you have Access to the windows folder, like the main system windows folder. Doesn’t that mean you can literally easily delete that folder thought the program?? Or will it just not let it do that. I wanna try it on a virtual machine
Okay but why?
Why delete the folder?
yes
I’m not saying I’m gonna make a game that’s randomly going to delete your windows lol, I’m just curious if it’s that easy to just delete important folders thought a simple script
Reminder.. Don't buy Juka's game..
You die you get random ass files deleted form your pc
Personally sounds like a good concept to me
i added third person camera from starter assets and my project broke
Hello I disabled autorefresh to be able to use hot reload, but unity is still refreshing
Any idea how to solve it ? thank you
Have you tried to reopen the project?
Might have been an error that happens once
Umm... Is that even the correct settings tab?
TryGetComponent already exists and does this already and more performant
Yeah autorefresh has been moved there apparently
oh nice, I hadn't come across that function before. Thanks!
Autorefresh not working
RaycastHit[] raycastHits = Physics.BoxCastAll(refCollider.bounds.center, refCollider.bounds.extents, transform.forward, Quaternion.identity, raycastLength, 0, QueryTriggerInteraction.Collide);
raycastHits = raycastHits.Concat(Physics.RaycastAll(ray, raycastLength, 0, QueryTriggerInteraction.Collide)).ToArray();```
My `Physics.BoxCastAll` and `Physics.RaycastAll` are not returning anything. Where am I going wrong? At first I suspected it was bc all the cars use trigger colliders, but I placed a default cube in the scene and the array length is still at 0. (Used concat just to see if either one is working)
the "refCollider" is the one you see in front of the car
0 is not a valid layer mask
..god damn it
If you want a layer mask that targets all layers ~0 might work
~0? with the tilde?
Physics.AllLayers is much more reasonable
Physics.DefaultRaycastLayers takes the ignore layer into account
How do I utilize A* pathfinding in a way which would base calculations on count of travelled roads instead of distance between nodes in such a graph?
Just set the same distance between nodes. Donno what A* implementation you're using, but there should probably be a way to pass in a collection of nodes and/or edges. When you create that collection you just set the same distance between all nodes.
It's just that for now my calculations of HCost are only between the currently processed node and the goal node. So I don't know how to calculate it this way if they are not neighbours
What are you using for A*?
Messing with the algorithm in an asset actually, so not sure...
https://pastebin.com/zDnXM8ix
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.
How do you calculate the HCost?
For now it's
private static float HCost(Node curNode, Node goalNode) {
return Vector3.Distance(curNode.transform.position, goalNode.transform.position);
}```
Which doesn't suit my needs
Just return 1
Thats 1 cost per step
The algorithm doesnt care about the physical layout
That and Map.FindValidPath should calculate the path distance based on the number of jumps.
Is there a good alternative for [Header("Textures")] that will properly group together a group from a parent class with the same group in a class that inherits it?
in the inspector
A custom inspector/editor!😬
can someone help me im so confused lmao
im doing animations and i tried to set up a death animations and im going down a rabbit hole
Is your issue code related or rather just about animations? #🏃┃animation
code related
ok
@oak plover did you manage to solve the animation event issue?
uhh so it got worse we can go into the thread lol
Oh the issue was already known, sorry to ask then. If you got a thread, feel free to invite 🙂
how do i make a Func delegate take any type of parameter? (edit: this is a general c# question)
Func<AnyType, SomeType> function;
How do I extract only Y axis rotation from quaternion?
I remember there's a way to do projection on plane
but I don't remember specifics
Generics or object boxing.
Quaternions have an eulerAngles property, if you just need Y you can get it from that
I have two direction vectors and I rotate object between them on Y axis.
How can I know in which direction rotation would be faster?
As of now I do rotation using const offset and to make a turn left, object makes a turn to right until it reaches left 😅
For now it's just like this
var rotationOffset = quaternion.RotateY(cs.rotationSpeed * deltaTime);
transform.rotation = math.mul(transform.rotation, rotationOffset);
just need to save a function to something inside a struct, and to be able to call it later, what type should i use?
A delegate that matches the function signature. Or a Func/Action.
how exactly would i use a delegate, been a while since i last touched them, and delegate void seems to not let me call the function for some reason
nice, that is literally what I'm currently reading, I'll reread it though lol thanks
Why not use a Quaternion helper method?
which one?
Either lerp or rotate towards based on your explanation.
I can't use lerp, because rotation logic is stateless
Then rotate towards
eh, I can't really use it, since I need vectorization friendly functions. But looking at it's source gave me enough idea
Wdym? It's not any different from what you're doing now.
I use Mathematics package library
quaternion and math types
and it's quaternion doesn't have such methods
Vector3.SignedAngle to find the angles towards those directions around a single axis
Aah
Simply checking Quaternion.Angle can work too but its around any axis
I cannot seem to get this to work, I know I'm doing something very wrong. but i cannot call the delegate void, it just won't let me, because i haven't done anything correctly lol. Could you link to some examples perhaps, as I'm very lost and google isn't pulling anything up...
Share your code
Huh, k
cross product did the trick
hey everyone, if i were to do rb.AddForce(dir * force);, how would i make the dir go from Axis space (like x = 1, y = 0 for forward, etc) into the actual direction that the object is facing?
AddRelativeForce
right now, it doesnt factor in the rotation of the object
ah that sounds like what i need
Or multiply the force with a rotation
boiled down code, because my code is a mess: ```cs
struct SomeStruct
{
public delegate void SomeMethod(); //crashes visual studio's CSharpWrappingCodeRefactoringProvider upon typing
}
public void Nonsense()
{
//does something
}
public void Chaos()
{
SomeStruct Something = new();
Something.SomeMethod = Nonsense;
Something.SomeMethod() // cannot be used like a method
}
how would i calculate how much force it takes to just overcome the friction so it stays the same velocity?
when in a non-accelerating or decelerating state
Delegate creates a type, you need to actually give it an object to use.
private struct SomeStruct {
public delegate void SomeMethod();
public SomeMethod MySomeMethod;
}
public void Nonsense() {
//does something
}
public void Chaos() {
SomeStruct Something = new();
Something.MySomeMethod = Nonsense;
Something.MySomeMethod();
}```
Not sure why it crashes for you though
ah ok thanks, so should i have a delegate void for each of the function fields i want to have on the struct, or is sharing 1 between multiple ok?
I prefer using Actions though, avoid whole declaration thing
Actions sound familiar, I'll look into them quickly then, thanks
Understand the Action type. An Action is a delegate that is similar to a void method.
thanks
ah ok now the struct works, now I just have to see if it is possible to get a list or array of the struct! (probably won't be possible due to the fact that structs in lists have to be non-nullable value types, but I can try, and if it isn't possible then I can just redo my code to not need a list of it)
mutable structs are bad, use class instead
What you have turns into this
private struct SomeStruct {
public Action MyAction;
}
public void Nonsense() {
Debug.Log("Message");
}
public void Chaos() {
SomeStruct Something = new();
Something.MyAction = Nonsense;
Something.MyAction();
}```
And you can also subscribe multiple actions to one...
ooh fascinating, I have heard of mutable structs before, I'll look into it, thanks
structs in lists... really, just use class
cool!
never have tried a list of class, so I'll try it thanks
Yea, if you are trying to store a bunch of methods just keep list of actions
or if you need to trigger all of them, subscribe them
just tryna clean up my code to be more readable, cause this is for ui, and each menu has a setup function and an every frame update function, and having them sprawled out everywhere is a nightmare, and having a nice simple WhateverMenu.SetupFunction, and stuff like that should make it more readable, thanks
myAction += myAction1;
myAction += myAction2;
myAction.Invoke();
if it was a class, it would be a reference type then, wouldn't it? So I'm probably going to stick with struct for now, atleast until i understand stuff a bit more lol, but thanks lol
btw is there anyway to force the struct to be non-nullable and a value type or am i going to have to get rid of the list and redesign some stuff?
value types are non nullable by default
ah ok good, so now i just need to make the struct a value type then
structs are value type
then why can't i have my struct in a list?
Who said that you can't?
visual studio, also i probably should have specified that it was a native list, cause there might be differences between regular lists and native lists that i don't know, sorry
That's a native list. You kinda forgot to mention the important part.
are you doing DOTS?
sorry, I often forget that native containers ain't the default... and yes I'm using dots
Well, then you should also know that you can't use any reference types in DOTS(you can on the main thread, but seeing how you use a native collection you probably want to use it in a job?)
delegates are reference types btw
I think
Yeah, it is.
you can't have reference types? I have quite a few reference types in lots of places lol, ah well hopefully it won't do much harm...
As long as they're not used in a job, it's fine.
ah unfortunate
ok that makes sense then, and I'm not planning to use this specific list in a job. Perhaps i should just use a regular list then, as I'm not going to be passing it to anything that despises managed code?
ok thanks, sorry for my foolishness lol, and i have no clue what the difference is between making it a class vs a struct, but sure I'll use a class lol, can't do more harm than i have already
The main difference is reference vs value type.
fascinating
when you store it somewhere it makes copy...
ah, so like a foreach loop's inner magic thingy (I don't know the name), only for every time you put it anywhere? I think i get that, cool
not quite sure about that, but carry on!
Not worked
if I cast e.g. 3.5f as (int), does it round down, up, or just discard the decimal part?
Ah fair enough
sorry i was super tired and probably should’ve explained more but yeah pun classic, by outdated i mean i don’t know if it’s been updated in a while bc it’s not working how it should for me- like shouldn’t it first ask me for my app id? bc once i import everything it doesn’t and i’m not sure why
this is even when i import pun 2
i got it working!!
using Photon.Pun;
using Photon.Realtime;
(VISUAL STUDIO 2022 QUESTION)
how do i make it so that VS displays all params docs? (you currently have to fill everything slowly to see it)
not very important cuz you can just click it in VS to see full doc, but just curious
why is this happening-
trying to get my character to do a backflip but this code makes the character go crazy and fall out of the level. What am I doing wrong?
probably more than one thing
- this sets a transform rotation, if your movement is using physics, you may want to consider rotation by adding torque instead
- you're comparing float values, the rotation may end up being very close to -360 but not quite and miss the condition
- other code may be interfering with this coroutine
depending on what you're aiming for here, I'd consider separating the visual backflip from any physics/movement controller. Make it an animation instead
hi
public GameObject videoPlayerObject;
private void Start()
{
Debug.Log("videoPlayerObject"); //WORK
_socket.On("receiveVideoURL", (response) =>{
Debug.Log("videoPlayerObject"); //NOT WORKING WHY
var url = response.GetValue<string>();
Debug.Log($"Received video URL: {url}");
console.log(videoPlayerObject)
});
so i can't .play() video
idk why
What's _socket? is the callback called on the main thread? If it's on a different thread, some unity api, like Debug.Log would silently fail.
It's not just the debugging, it's really everything that can't be called,
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 send you a past
Unity API
so how i can do it ?
Many ways.
Raise a flag and consume it on the main thread for example.
Can you give me an example?
Did you read the documentation of the SocketIOUnity?
Here. They even explain how to sync with main thread.
https://github.com/itisnajim/SocketIOUnity
Yeah, andthere are a lot of libs that don't work anymore, this is the only one I even looked at examples but I don't see
let seee maybe wrong doc
Why not use unity transport btw?
UnityThread.executeInUpdate(() => {
coz i want a server control (nodejs) for action
Hmm
Pretty sure unity transport should work as well.
It has it's own sockets implementation.
But maybe I'm wrong.
Hello, quick question, how can I convert a cubemap into an sphere from code?
working with that @cosmic rain thanks.
Hey! I need some help with meshes. I am currently migrating a project from three js to unity and I have a geojson with latlngs that I am using to make a three.Shape (https://threejs.org/docs/#api/en/extras/core/Shape) The shape has something called holes and this is very useful as I just give it a path for the outer bounds of the polygon that I have reformated from the latlng with mercator projection and then I give it the holes inside of this polygon (in the same format) and it calulcates everything for me, but I can't seam to find a good way to do this in unity. Can anyone help me out? I have multiple ideas, either to make multiple meshes and somehow "cut" one out from the other (like boolean in blender, this is they way I want to avoid) or in c# somehow calulate and triangulate it with the holes, but how do I do that?
so i have made a build and send it to a friend to test multiplayer and i would like to see his log files but i cant find them anywhere and everything on the internet says something about a folder that i cant see
hey guys
ok wtf i just got chatgpt to write a first person character controller script for me wtf
I'm sure that microsoft will compensate you when you get it to generate code that crashes your project. 😄
true kek
it works 😎
I have severe crash issues, just managed to catch one crash while profiling, what could be causing that?
Not directly related, but the WaitForTargetFPS is because you have VSync on
Looks like theres a lot of garbo collection going on 🤔
Also look at your crash logs to see if you find any clues
The game isn't crashing, plus where can i access those logs on android?
Well... it`s not a "crash"
https://docs.unity3d.com/Manual/LogFiles.html scroll down
it's hard to explain!
So, Sometimes, while the game is running (on my quest 2) it hangs itself up, it doesn`t render any new frames and is just stuck on one while sound is still playing, then if i put the headset on standby and back on, there is a terrifying visual glitch happening, as seen here:
At the end of the video you can see how it's supposed to look.
As you can see, the meshes get messed up aswell
I have a question, how does the unity layer system work? I want to create my own similar to it because the way I want to do it won't work with unity's own layer system. Basically I want to make a 2d game that includes jumping and platforming, I haven't made the code yet but the basics of it are there is a jump button that increase the player's sprite renderer y value and a float called height level, when this jump is over gravity is set to 1, and when the height level is equal to the floor level (another float) the gravity = 0. When the player gets on a platform their floor is set to another value with an on trigger enter and exit 2d function, and that's it. I want certain colliders to be non interactable for certain entities based on that entity's height level. Is there any way I can do this?
guys i have 2 errors im trying to implement unity ads and im using a template that already has unity ads. when i clicked the on button to monitize these errors popped up. any fixes?
anyone can help me?
not comptatible webgl i think fuck
i see someone talk about a* above
are there any guys know what is the stopping condition of bidirectional a*?
i read some python codes,
one is just frontier of forward search==frontier of backward search,
some of them is max(top of two heaps) <= minimum predict value (i read a pdf on is similar to this but <= minimum predict value + certain value),
i wrote my a* based on second one but i am not quite sure
wdym stop condition?
either you have reached all nodes or your stop early when you found what you were searching
ah nevermind, bidirectional
for dijkstra, the current node is always the best path so far, so with bidirectional you just stop when you meet.
a* uses a heuristic on top of that, sacrificing perfection for speed, so you can also stop when you meet and accept that it might not be 100% ideal path
if you want a perfect path, you shouldnt use a* anyways
a* is complete if h is not overestimate ofc my h may not be perfect
yes if you would let it finish. but im not sure about that if it meets inbetween
i have considerd implement bidirectional bfs but it is quite slow compared with a*
although it guarantees return a shortest path
bellman forde is worse than dikjstra and a*, only useful if you must have negative edge values
dont know your use case, but you can jsut scale back the weight of the heurisitic. the closer it gets to zero, the more A* turns into dijkstra. just try out and use what feels right
it should independent from use case, the beauty of math and algorithm but i am poor in discrete math so i cant enjoy it
you have to put restrictions in anyways. bellman forde has them too
it will crash on negative cycles iirc
some paper on NBA* but i cant fully understand it...
I'm having some trouble getting Netcode for GameObjects to work, I managed to create a manager and run a host and have a client connect to it, and I added Client Network Transform and Network Object components, but the clients who connect to the host still can't move. Anyone know what the issue might be?
I'm following this tutorial for NGO btw: https://www.youtube.com/watch?v=3yuBOB3VrCk
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubre...
Netcode for Unity is an amazing real-time multiplayer solution, which is part of the wider Unity Gaming Services.
Checkout Netcode: https://on.unity.com/3blzOy3
In this video you'll learn:
How to get started with Netcode
The different between server & client authority and when to use each
How to write performant network code
How to use Networ...
Try this one instead. Tarodev usually has the repo in the description available.
thanks! I'll take a look
Hello, I'm trying to wrap my head around some logic. I have about 10 cubes that moves from point A to B. I also have a separate manager class to control the logic of the level.
I was thinking about firing an event when each cube finishes moving from A to B and then my level manager can listen to this. The problem is that I would need a reference to each of those 10 cubes in my manager?
I'm trying to find a way to dev this that I can use that cube logic in any level without hardcoding too much. Any suggestions on how to go about this?
One way to approach this is to use a script that can be attached to any game object that needs to move from point A to B this script can have its own event that is fired when the game object reaches point B your level manager can then listen to this event without needing a direct reference to each game object instead it can simply search for all game objects in the scene that have the moving script attached and subscribe to their events
Should I be using scriptable objects for anything I intend to spawn in and out at a high frequency? Or for use cases that don't need to store more than a few variables should I continue to use pooled GameObjects with monobehaviours?
for objects that need to be spawned and destroyed frequently, like bullets, particles, or enemies, using pooled GameObjects with MonoBehaviours can be more efficient, so depends what ur using it for
Ahh that makes a lot of sense! Thanks @civic fern ! I think I'm mostly there all I would need to do is add the code to find the game objects with the Movement script and subscribe to all their events and it should hopefully just work - I'll try this now!
Im spawning a bunch of projectiles that are affected by various forces non of wich I would like to get the rigidbody component for at runtime and before I start storing things other than gameobjects in my pooler I want to make sure im not going about it wrong. Its just a rigidbody for now but I use this pooler to pool everything that spawns at runtime more or less and would prefer it to be very lightweight and simple
If you don't want to get the Rigidbody component at runtime, you could consider adding it to the prefab for the projectile, so that it's already attached when you instantiate the object this will be more performant than trying to add the Rigidbody component at runtime if you're concerned about the memory usage of storing other components in your pooler, you could consider using a lightweight alternative like structs or simple data classes to store the necessary information however keep in mind that this may make your code less flexible and harder to maintain in the long run ultimately it's up to you to decide what approach makes the most sense for your specific use case and performance requirements. If you're unsure, it's always a good idea to test and benchmark different approaches to see which one performs best in your game
Im still getting the "Projectile" class with a getcomp call in that case though right?
Yes, if you want to use the Projectile class for your projectiles, you will still need to get the Rigidbody component from each spawned projectile.
However, you can minimize the performance impact of this by caching the Rigidbody component after getting it once and then reusing the cached reference for subsequent updates. For example, you could add a private Rigidbody rb; field to your Projectile class and then cache the reference in the Start or Awake method
then in your update or fixedUpdate method, you can use the cached refrence instead of calling getComp everytime
ok cool. That was more or less the plan I just wasnt sure of this was the intended use case for scriptable objects since ive avoided learning about them them like the plague
do you have a screenshot of your game?
Should I be using scriptable objects for anything I intend to spawn in and out at a high frequency?
no. you use a pool of prefabs
Instance objects --> get components --> set active as normal now all that is at start but what's 300 getcomponents all at once? lol
or whatever my pool size is
much preferred to at runtime though
scriptable objects make sense as data containers of string, float, int, struct fields. if they reference rendering data like textures and sprites, you are usually better off with a prefab. if they reference prefabs, you are making a design error.
if you are adding code to a scriptable object class, you are making a design error
sure do, let me just get it running
TYVM! @civic fern @polar marten
you can make the manager a singleton, and the cubes call a method on it.
you're at the start of a long journey
what version of unity are you using?
