#💻┃code-beginner
1 messages · Page 768 of 1
what's the goal here exactly?
I want to make sure any ground below the direct center of the character controller is no further away than the cast length
What's with the SKIN thing though
It's a constant for 0.01f. Mostly to make sure there's actually somewhere to cast from
I'm having trouble visualizing this honestly, and not sure I understand the purpose of SKIN or this Approximately check
by definition a raycast won't detect things further than the max distance you use in the raycast call
If I cast from rb.position it's never going to find the ground below it
why not?
where is the RB position? Where's the pivot of the object in relation to its colliders?
As far as I can see I don't have a max distance. Is that assumption erroneous?
yes, that's erroneous, Raycast has a maxDistance parameter
if (Physics.Raycast(rb.position + Vector3.up * SKIN, Vector3.down, out RaycastHit metaHit, groundingMask)
In fact I'm pretty sure you plugged your layermassk into the maxDistance parameter here
which is a common error
It does, but you don't need to put it there. I'm asking if it's reading groundingMask as the cast distance
It doesn't make a difference anyway given it still hit SOMETHING and I confirmed it using a cast length that should register a hit for sure
there's nothing special about rb.position as the origin of the ray
What is this for, a grounded check?
Yes
I'd visualize the ray/hit with Debug.DrawRay/DrawLine
Yeah ^ you should definitely do this
(Or physics debugger)
and double check your layermasks etc, since we know now you had it in the wrong parameter spot
Shifting it doesn't make a difference
it would be nice to see screenshots of the game/scene view alongside the actual code here
This is all there is to show
It's touching the ground. It just spawned at this point. That's why castLength is zero
I'm casting from a spot that is intended to be Vector3.up * 0.01f higher than that point and casting it straight down
Then seeing if that length minus 0.01f is approximately equal to the castLength which is zero
wait castLength is 0?
That's definitely a problem
castLength is not actually used in the raycast
It's just something to compare hit.distance to
Or rather metaHit.distance
The best thing to do would be just to do a raycast from the center of his body down slightly longer than half his height
so if he's 2 units tall, do the cast from the center down 1.01 units or something like that
There's no need to be doing this distance comparison stuff
This is the code once again
if (Physics.Raycast(rb.position + Vector3.up * SKIN, Vector3.down, out RaycastHit metaHit, groundingMask) && Mathf.Approximately(metaHit.distance - SKIN, castLength))
{ grounded = true; }
else { grounded = false; }
if (!grounded) { print((metaHit.distance).ToString() + ", " + castLength + ", " + Mathf.Approximately(metaHit.distance - SKIN, castLength)); }```
you still have groundingMask in the maxDistance slot
It's also not clear what hit.point is infloat castLength = hit.point.y - rb.position.y;
the result of some other raycast?
Ok
if (Physics.Raycast(rb.position + Vector3.up * SKIN, Vector3.down, out RaycastHit metaHit, 10, groundingMask) && Mathf.Approximately(metaHit.distance - SKIN, castLength))
{ grounded = true; }
else { grounded = false; }
if (!grounded) { print((metaHit.distance).ToString() + ", " + castLength + ", " + Mathf.Approximately(metaHit.distance - SKIN, castLength)); }```
It's still giving me the exact same result
Well yeah it's not going to change the distance at which the raycast hits
The issue is this whole Mathf.Approximately(metaHit.distance - SKIN, castLength)) business in the first place
just get rid of that
(btw you could just set grounded to the bool physics.raycast returns here)
and use maxDistance as intended
If I do that then of course it's going to register as false because of floating point inaccuracy. The point is to account for that
why would it?
Either you are overthinking it or we aren't getting it
grounded = Physics.Raycast(rb.position + Vector3.up * halfPlayerHeight, Vector3.down, out RaycastHit metaHit, halfPlayerHeight + 0.01f, groundingMask);```
this is assuming the player's pivot is actually at his feet^
And this is what I'm doing except halfPlayerHeight is just 0.01f above the player's feet
if it's in the center of his body it would be:
grounded = Physics.Raycast(rb.position, Vector3.down, out RaycastHit metaHit, halfPlayerHeight + 0.01f, groundingMask);```
Hello, I'm new to unity and programming in general. I have completed a few courses that utilized the old input system, but now I'm trying to use the new input system now since I've heard its better. But I'm struggling a bit, specifically with code arrangement and optimization. I'm wondering if there is something that I'm doing severely wrong in my project thats causing a major bottleneck (project is compiling signifantly slower than usual). All I have in the scene right now besides the standard objects unity provides (main camera, directional light, and global volume), is a plane object acting as my ground and a cube for my player. And I only have one script as of right now for my player. Any help would be greatly appreciated. Here is my code: https://paste.mod.gg/lfcbhvwcznvo/0
A tool for sharing your source code with the world!
You can use assembly definitions to reduce script compiling time. However, if your scene is quite empty.. it's probably due to assets. If they aren't properly addressing assembly definitions, you could probably configure something for them as well 
It really depends on what's the actual limiting factor.
My project is basically empty. So its most likely not due to assets. I figured my code using the new input system was the culprit
Because tbh I'm not entirely sure what I'm doing with it yet still lol
How much slower is it and what's actually loading? You ought to get that loading pop-up that would state what's actually being processed atm
I think I may have used the wrong term. I'm not talking about the code compilation time, but the scene compilation time when you press the play button. Which I think the code is impacting
Went from like 5 seconds max to like 15 seconds
15 seconds isnt that bad
It is when you're project is basically empty
I guess I can try to close out of some other programs and hope that helps unity run faster. Doesn't sound like its bad code or anything
You could use the profiler to see what takes most of the time. Maybe the logs have info on that too.
!logs
Editor logs
Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log
Unity Hub
Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs
are you by any chance referring to the Domain Reload? because you can actually disable that from happening on entering play mode (there are caveats to doing so though)
https://docs.unity3d.com/6000.2/Documentation/Manual/domain-reloading.html
Yea that's what I was referring too. Not sure if a beginner like me should disable that though
provided you read that information and understand what it means, you can. otherwise you just have to deal with it
Domain reload timings are logged in the logs. Could maybe have a look to see what takes most time.
My game display’s the player’s current y position as well, and i tend to have a similiar problem.
I believe there was a Mathf function that checked if a variable was really close to a number?
Approximately
You can use that function and combine that with Mathf.Round to avoid annoying numbers
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
coming back to this, trying to figure out why I can press W and D and move in those directions, but can't move in A or S
if (Input.GetAxisRaw("Vertical") == 1)
{
rigidBody.AddForce(transform.TransformDirection(0, 0, force * Time.deltaTime));
Mathf.Clamp01(force);
}
else
{
rigidBody.linearVelocity = Vector3.zero;
}
if (Input.GetAxisRaw("Horizontal") == 1)
{
rigidBody.AddForce(transform.TransformDirection(force * Time.deltaTime, 0, 0));
Mathf.Clamp01(force);
}
else
{
rigidBody.linearVelocity = Vector3.zero;
}
I tried this before, and got to it work, but it turned into 4 seperate if else lines
and i had to use GetKey
and use the corrosponding key
But i want to be able to use controller, so i'm trying to figure out how to use the axis
my theory is that it's because it's not going in -force when using negative buttons
I dont see you debugging your getaxisraw value. Are you sure, it hits 1? Also, you are forcefully putting it to zero even on 0.9999999, because thats not 1, so not sure, its intended
public class Movement : MonoBehaviour
{
public int force = 1000;
/*[Range (0f, 100f)]
public float tSpeed = 50;*/
Rigidbody rigidBody;
void Start()
{
rigidBody = GetComponent<Rigidbody>();
}
// Update is called once per frame
private void Update()
{
Mathf.Clamp01(force);
var horiz = Input.GetAxisRaw("Horizontal");
var vert = Input.GetAxisRaw("Vertical");
Debug.Log($"horiz {horiz}");
Debug.Log($"Vert {vert}");
}
private void FixedUpdate()
{
if (Input.GetAxisRaw("Vertical") == 1)
{
rigidBody.AddForce(transform.TransformDirection(0, 0, force * Time.deltaTime));
Mathf.Clamp01(force);
}
else
{
rigidBody.linearVelocity = Vector3.zero;
}
if (Input.GetAxisRaw("Horizontal") == 1)
{
rigidBody.AddForce(transform.TransformDirection(force * Time.deltaTime, 0, 0));
Mathf.Clamp01(force);
}
else
{
rigidBody.linearVelocity = Vector3.zero;
}
}
}
full code
I am debugging it, it does respond to me pressing S and A
but it simply will not go in those directions
don't worry about that mysterious clamp at the top, i have yet ot remove it because i'm still figuring this one out
i'm still fairly new
Just read your code carefully. Describe what it does to your velocity. Just because your horizontal value is changing the force, what does your vertical one do?
if you do not hit a button/key
if I don't hit W or D, it won't move (vertical and horizontal reacts the same)
right, what does your code do when you do not hit w or d?
now that you point it out, is it just that because the force is not meant to be negative, it automatically uses the else scenario even when I use A and S?
because if i'm not pressing W or D, it stops
you are setting your velocity hardcoded to 0,0,0
linearvelocity right?
So if you hit horizontal input, your vertical one is still killing the movement in the next fixed update frame
and because it's killing input, it's pretending like it's not being pressed?
no, its stopping your rigidbody
might have to go a little deeper, not sure i'm getting it.
because would A and S be -1?
you tell me. Thats why I said, debug your getaxisraw
so == 1 wont work
thats ONE part that might stop your code from working
ok so I pulled that while search of a way to make a float do a bools job, uhh..
would you be willing to help me understand what that was?
firstly, you want to be sure, that both inputs are being accepted. so you can have either a check for 1 and -1 or you could transform the getaxisraw to be always positive, so == 1 works for both scenarios
well, i know both inputs are being accepted, so if i set it to 0, wouldn't it stop moving?
do i need to get 2 more if else commands in order to make this work
with -1
In the code above, if either statements with horizontal or vertical are ever false the else will have your velocity be reset to zero.
correct
that is the intention
I mean that your if statement accepts both 1 and -1. so you either can write
if(MyInputValue == 1 || MyInputValue == -1)
or you could write
if(Mathf.Abs(MyInputValue) == 1)
or even better
if(Mathf.Approximately(Mathf.Abs(MyInputValue)) == 1)
Just written here in chat, so check the syntax 😄
Horizontal being checked after vertical would be able to recover it's added force but vertical velocity would always be zero if horizontal is false
and even if it works for the fixed time rate, it still wont have the result you would expect from adding force, when resetting it in the next frame
But as a follow up on my suggestion, you might end up in another code anyway as soon as you want your input value to be considered as direction for your force
So just for clarity.. you will not have any movement if a and d are not pressed (regardless of the state of w and s.
that I also realized, which was something i somehow figured out with the last bit of code
wait, maybe i'm dumb, but using Keys WASD would have the same affect as Updownleftright? right?
You might want to store the linearVelocity after adding the force and then only control the axis you want to control to 0 when not pressing any button for either one of the directions
It might be better to cache your input and do a single check later to see if any input was pressed at all before setting velocity to zero:```cs
int vert = Input.GetAxisRaw("Vertical");
int hori = Input.GetAxisRaw("Horizontal");
if (vert > 0)
{
rigidBody.AddForce(transform.TransformDirection(0, 0, force * Time.deltaTime));
}
else if (vert < 0)
{
rigidBody.AddForce(transform.TransformDirection(0, 0, -force * Time.deltaTime));
}
if (hori > 0)
{
rigidBody.AddForce(transform.TransformDirection( force * Time.deltaTime, 0, 0));
}
else if (hori < 0)
{
rigidBody.AddForce(transform.TransformDirection(-force * Time.deltaTime, 0, 0));
}
if (vert == hori == 0)
{
rigidBody.linearVelocity = Vector3.zero;
}
else
rigidBody.linearVelocity = Vector3.ClampMagnitude(rigidBody.linearVelocity, force);
I feel like i'm understanding more than I did before because of the my lessons, but I think i'm still confunes on a fair bit of things
But you want both buttons to work? W/S and A/D ? or did I get this wrong?
yes I want to use both WS and AD, but am only capable of using W and D
yes, so you need to transform your negative axis value to positive to not need to check for two values. Thats what I wrote up there
I am sure dalphat can adapt the code to use mathf.abs quickly here 🙂
would that just be a seperate if statement before the getaxis statements
careful dalphat, I may ask you how it all works for clarification if you do
its just the bool lines changing the
Input.GetAxisRaw("Vertical")
to
Mathf.Abs(Input.GetAxisRaw("Vertical"))
and same for horizontal
Mathf.Abs will turn your values into absolute numbers, always positive
so they'll always be 1 and 1? not -1 and 1?
which, don't I want -1 and 1?
since negative utilizes -1
the bool check will check for 1 and 1, but the input value is of course -1 and 1. You just transform it in that line to avoid two if statements
so it'd be something like if (Mathf.Abs(Input.GetAxisRaw("Vertical") == 1)
{
like that?
still a little confused on.. how that'd work
you are missing == 1 in your example
cannot convert from bool to float
basically this line
if(Mathf.Abs(Input.GetAxisRaw("Vertical")) == 1)
says. If the absolute value (the always positive one) of your input axis (which can be between -1 and 1) is 1, the condition is met.
ohh ok I see, so what's the == 1 for in this case if it's already checking for an absolute value, still got the issue of cannot convert bool to float
bool to float? where?
I am big dumb dumb, Parenthesis was in wrong spot
😄
time to see if it works as intended.
if (Mathf.Abs(Input.GetAxisRaw("Vertical")) == 1)
{
rigidBody.AddForce(transform.TransformDirection(0, 0, force * Time.deltaTime));
Mathf.Clamp01(force);
}
if (Mathf.Abs(Input.GetAxisRaw("Horizontal")) == 1)
{
rigidBody.AddForce(transform.TransformDirection(force * Time.deltaTime, 0, 0));
Mathf.Clamp01(force);
}
else
{
rigidBody.linearVelocity = Vector3.ClampMagnitude(rigidBody.linearVelocity, force);
}
well,
A and S work, just not in the right direction
so that's at least a step in the right direction
Please use code tags 😄
will try to
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so changing both negatives into positives just makes them go in the positive direction right?
because that seems to be what it's doing
Nope. it just tells you rcode to get into the if statement. Currently you do not use your axisvalue anywhere else to dictate the direction
..alright, so, how would I go about assigning direction, would I just copy and paste the if and make to more if's
and set the 1 to -1?
lemme see
store your if statement into a bool, as dalphat suggested. and store your input correct values (not absolute) into two floats you can reuse then
i feel like at this point my original code probably worked the same and just needed to be cleaned up
public class MOVEFORWARD : MonoBehaviour
{
Rigidbody Rigidbody;
[Range(15000f, 50000f)]
public int force;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Rigidbody = GetComponent<Rigidbody>();
}
public void FixedUpdate()
{
}
// Update is called once per frame
void Update()
{
Mathf.Clamp01(force);
Rigidbody.linearVelocity = new Vector3(0, 0, force);
if (Input.GetKey("w"))
{
Rigidbody.AddForce(transform.TransformDirection(0, 0, force * Time.deltaTime));
}
else
{
Rigidbody.linearVelocity = Vector3.zero;
}
if (Input.GetKey("s"))
{
Rigidbody.AddForce(transform.TransformDirection(0, 0, -force * Time.deltaTime));
}
else
{
Rigidbody.linearVelocity = Vector3.zero;
}
if (Input.GetKey("a"))
{
Rigidbody.AddForce(transform.TransformDirection(-force * Time.deltaTime, 0, 0));
}
else
{
Rigidbody.linearVelocity = Vector3.zero;
}
if (Input.GetKey("d"))
{
Rigidbody.AddForce(transform.TransformDirection(force * Time.deltaTime, 0, 0));
}
else
{
Rigidbody.linearVelocity = Vector3.zero;
}
}
}
a lot of clean up
i can get rid of probably all of those vector3.zero's
except for the final one
also not entirely sure what magic you're using, if i try to use those int's, i get an error
add force in update() for example is not something you should do.
yeah, realized that while I was looking back over it
can't readd it to the character now though, for some reason it has decided it no longer works even though I just used it
Your console will most likely fire an error
is there something to clear console through code?
Debug.ClearDeveloperConsole(); don't do it at least for regular logs
can someone DM me and help with adapting a GI script to VR? the onyl problem is renderTextures not beign set up right and me being dumb
been trying to fix this for 7hrs now
Thats just for debug builds, not editor. You need reflection and basically get the console window and get the clear logs button method to execute it
a quick google search will tell you what to do
Just write your issue our create a thread. Noones gonna randomly dm someone on a public server most likely
amusingly much hassle, but it works thanks
Not everything in editor is exposed for us to use
because they are corwards
Also wondering why you would want your console log to be cleared in the middle of script execution
in short I don't want to care about proper logging yet
so I shoved a bunch of debug logs inside a long method I want to check but it getting executed pretty frequently
Well, then clearing the log is not the issue 😄
the actual solution takes less effort that trying to clear the logs all the time
are you sure about that
because I just copypasted random code (which may cause mild memory leak by creating objects each time used? but whatever) and it works
is there a constant that is hooked onto assets? i need something that are shared among all kinds of assets(e.g meshes/animations/images/textures/materials)
yeah I doubt that making logging out properly would take more time than doing what I did but I would have to go get distracted out of what I do right now and learn something else
instance ID?
what's the use case
might be edge cases but they probably all inherit from Object
im migrating SO data into cloud save, but multiplayer side coding isnt the problems here, my question is, i need a reference, or a constant that can refer back to the exact asset in the project
because no way i will throw the exact model/material inside the backend right?
addressables something something?
generate your own GUID, or during editor serialize the asset ID via on validate
yes everything that inherits from object should have instance id
it's always unique
why not
you'd have to look at how this is used on full but boss room sample implements that kind of idea https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Infrastructure/NetworkGuid.cs
if i understand correctly he will keep all assets in the project
its not consistent between sessions
shame
I wish I could comprehand what's the issue is, I can't help but curious
I know that SO is a scriptable object, what is the issie of putting it onto cloud save?
lets say we have bunch of items, boxes ? maybe
the box will have size, some attributes (weight....etc) , and u might need to have a reference to certain texture right? , no way ur boxes will be all white or plain color
but , what if the texture is huge? or any other highly complicated datatypes
how to generate a unique value that you can "permanently" associate with an object so if i say like "FSEFR4TR4FGFGSD" that will always* mean say Crop_Ice_Harvest.png
and ofc, we have models, thats like more than 10mb if u want a more refined ones, u save that into server also? that will make ur cloud server explodes, so , instead of saving the whole thing in, we will save down a reference
and thats the guid were talking about
a constant that needs to be immutable in any situation
so when i grabbed the data, i can use that constant to find the asset in my project
so this is how to use cloud properly
the concept of it is a part of it yes
generally in networking a lot of stuff is too big to send over the network, so you need to find a way to send smaller info that communicates the same thing
eg. instead of an object in a list you just send the index
networking is a good way to learn how to make an actual save system that's for sure
optimized at that
yeah I was just getting away with small size assets and no thinking
I would rather work the other way around because I already know how to make a reasonably optimized save system
depend on how ur game looks like and behaves tbh
I guess
but if ur game got something that is larger than 10mb, i dont think its suitable for u to stuff the whole thing into backend
since I only did small things...
I just convert all save data in a single long string lol
almost as optimized as a JSON (I mean better but it's just a string)
which means it's bad but fine for small things
to take my chance I ll ask here what things are better
for saves I mean
like if u got lists of inventories and some transforms to save
json is not "optimised", binary serialisation formats are better
protobuf and bebop are examples
i think json is more universial/common and compatible to most of the designs?
thats why its popular
to save data for your own program, compatibility isnt a concern
makes sense
to store data you expect to be used elsewhere, then it matters
I was using string at one project and JSON at another because well it's a web game so
some games even use sqlite for save data due to its efficency and speed
just saying
Ofc for web we are restricted but you can serialize to a binary blob, convert it to a "string" and store it in local storage/elsewhere.
makes sense tho I can't figure out what to use to do that convertion
I suppose a string is a binary blob internally right
most common way is to a base64 string
interesting
i think my way to create GUID is using sha256 to hash the asset name
anyway as a beginner dont go trying all this if it confuses you too much
not how that works, a guid is just meant to be a unique identifier
assuming im not having duplicate names, and i remember to update my server side info consistently if i changed assets name
sha256 can be unique and constant identifier right?
you would generate a new guid and use that... thats it
^ yes use this
yeah I won't go into that now since well I need to get better at many other areas first but it's good to know for the future
so I don't make it like RimWorld where a savefile can be twice bigger than a whole game itself
tho I guess they keep it simple for modders
ty i will check on it 👍
Hey everyone! I’m Aaryash, pretty new to Unity and currently working on developing educational games for the Meta Quest 3s. I’m here to learn, explore, and hopefully get some guidance or insights from you all to help me with my research and project development. Would really appreciate any tips, resources, or experiences you can share!
Sorry to say, but this server does not work that way. You can come here with a question related to the channel you are asking in (in this case, paste your code and ask where you are stuck for example). And then you wait for answers to come in 🙂 A lot of people here are employed devs and hanging out on discord meanwhile, so we all pick our time share quite carefully. Welcome and feel free to ask anything, if its related to code in here or search for other channels. If you dont know exactly where to ask, just ask in #💻┃unity-talk and someone might tell you a direction where to go or answer your question there 🙂
Hey guys, I'm creating a movement controller that'll apply force to the character in WASD directions. The difference from regular solutions is that I need it to work reliably with different shapes. For example walking around sphere, I expect the character to be pulled down to vector -y (towards the ground), that's easy. But determining the right and left reliably seems more of a challenge.
It should work something like in Super Mario Galaxy, but character is ball (the physical model)
Or for example, walking on the sphere from inside out, on the walls. If the camera looks down on the character from atop, W should mean go up, if I look forward from the character, W should mean forward.
Can you guide me in direction of what methods I should implement to get this going?
I could add a raycast, for example, for forward and down, but then the ball is going to rotate, so that might not be it.
A collision normal sounds like the solution, but it only gives me vector Y, so I can't reliably get X or Z direction.
I'd really appreciate help on this one
Basically, my game is going to be a game where you're a droplet moving accross the inner sides of bottle. Camera will be top down view.
But also, there may be situations where you're on bottom of the bottle, or on some other surface
I am still trying to understand, what exactly you trying to achieve. This sounds like 5 different movement controls in one
what is your point of reference anyway
if it's camera use camera oritentation
if it's character use it's oritentation
Hmm.
Super Mario Galaxy is the closest
It sounds a bit like a sticky ball, that should be rolling on everything in the world
You just take the camera directions and project them on the surface normal
That easily?
Thanks, that clarified it for me at least
exactly
Is this the only good option that comes to your mind? Or are there alternatives?
Can I ask what you don't like about it?
So lets imagine a huge pipe and you can run from ground into a looping movement, your issue is, that for example going right will eventually turn into going left, because force is still going right relative to the characte rbut your camera view shows the ball rolling left on the top of the pipe
I've previously tried implementing a similar solution for my other prototype, and there were some issues, like the ball rotating in to the right (torque) when pressing D and looking down on it.
That may be a specific issue that needs fixing, but it seems to me, maybe there's more robust solution
The torque issue is unrelated to the controls issue though. That's just from friction
Do you want your ball to stick to a ceiling too, for example?
yes
But that's gravity, -y 9.8 for example.
the question is, do you need gravity?
No-no. Let me explain to you.
So on the wall, for example, I expect the ball to start rolling to the right relative to the wall. But it starts rolling to the right relative to the ground, because the Right from camera is pushing 90 degree right, while the wall may be outwards.
Or pressing W will push the ball INTO the wall, do you get me?
I guess?
How else the ball is going to be attracted to the surface it's on?
I am just thinking, if you could just add force into the direction you are moving your direction vector.
But I guess your issue, you want to go up but also want to go forward
My issue is that, I'd say, when looking at the character, I may not be looking perfectly forward from it's pov, but I still may want it go up "forward" relative to itself
So the W may mean forward, but it may also mean Up. It sounds like camera movement may be what I need, but in my experience it has introduced quite a few issues. Let me show you if I can catch one.
I guess you have no other option, if you dont want to use two joysticks to move 😄 But just looked at mario galaxy and from what I see, its mostly spherical gravity or hard coded rotated gravity. So if you jump over a ledge, it turns and moves gravity to another direction
How do they handle the direction of the charcater in Mario, what do you think?
Here is one of the issues introduced by it.
So, when I go W or S, it works nice. It goes up or down. (Also in this example gravity is always downwards, since it's my other prototype).
But when I go D, it doesn't rotate the ball relative to the wall. It starts rotating the ball relative to ground
This is how it does now
And this is how it should be doing
than you need to fix the rotation. But thats code, so show it 🙂 I gotta be off now, but surely others will chime in here to help. But in the end. you need to get the down vector point and the camera orientation to move and rotate the ball locally
So you think that's more of a bug than fundamental issue with the projection?
pretty sure direction is always relative tot he camera in 3d mario games
If you look at mario again, the character is rotated, right? It always orients its down vector to the plane he is on. Your ball is not I assume
Hm, interesting.
thats why rotation on D will rotate like the ball is in global space
so you gotta subtract/add the orientation of the plane the ball is on from the calculation to rotate the character
This is how my code looks like in regards to this
Vector3 cameraForward = assignedCamera.transform.forward;
Vector3 cameraBack = -assignedCamera.transform.forward;
Vector3 cameraRight = assignedCamera.transform.right;
Vector3 cameraLeft = -assignedCamera.transform.right;
// Project the force onto the plane perpendicular to the ball's up vector
Vector3 projectedForceForward = Vector3.ProjectOnPlane(cameraForward, Vector3.up).normalized;
Vector3 projectedForceRight = Vector3.ProjectOnPlane(cameraRight, Vector3.up).normalized;
Vector3 projectedForceLeft = Vector3.ProjectOnPlane(cameraLeft, Vector3.up).normalized;
Vector3 projectedForceBack = Vector3.ProjectOnPlane(cameraBack, Vector3.up).normalized;
#endregion```
But I guess it might not tell you everything?
How are you moving your ball? With forces?
Are you using torque to rotate it?
Both
Maybe a combination of dynamic parenting and https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Rigidbody.AddRelativeTorque.html and the force equivalent could also help.
My experience with parenting and applying relative forces never been that positive really.
Kinematic Character Controller has a lot of this behaviour btw. You can probably go download it and rip it apart to get a better idea if you're curious
a lot of the time the numbers do tend to be negative
Looking at my code, one thing that concerns me, it feels like I'm never actually projecting the up or down?
Like, here ```Vector3 cameraForward = assignedCamera.transform.forward;
Vector3 cameraBack = -assignedCamera.transform.forward;
Vector3 cameraRight = assignedCamera.transform.right;
Vector3 cameraLeft = -assignedCamera.transform.right;```
So I never use Y basically?
Would that cause the issue I'm having?
At the time when creating the ball controller the resources were pretty scarce
Anyways, thanks for the help guys. I'm still open to suggestions of how it could work in a more complete way, but I'll go try something I guess
I'm trying to make a 2d RTS top down game, Can someone give me some pointers to what I should research and learn to make them ?
google.. this question has been searched to death
I believe even codemonkey 🙄 has a bunch of rts 2d stuff you can learn about
thank you
i think there's something wrong with my visual studio.
is that 2026?
If you look closely the first i has an accent (´) on top of it (í)
wow good spot
ow foreign keyboard moment
unicode was a mistake, ascii only
not beginner code
Why is it when I extract a method from my code (2nd image) it changes into the first image's code rather than just simply saying "HandleShoot();" ?
Following a course and theirs ends up different from mine when I extract my method, pretty sure it still works, I just want to know why it does that
because VSCode sometimes is weird like that
probably just to handle the return "correctly"
btw ?. doesn't work proper on UnityEngine.Object / Components
use the == null check
or better yet , TryGetComponent
(in general you shouldn't rely on those kinds of tools to be exactly what you expect - they're there to save time, not to replace work. oftentimes you will have to tweak various suggestions to get exactly what you want)
considering the specific usage here, it would "work" for the possible situations right? would GetComponent give a deleted component
(in "technically works" terms, not saying ?. should be used)
Yeah, ever since i got 2026 it's been pretty buggy
and annoying
i miss having the 2022 version
you could just get the 2022 version if you want
It's support ended just recently right tho?
i kept having popups
and couldn't use it anymore
That's soo hard to notice. Thanks for the help
ah, subscriptions/licensed support bs. mb.
I guess its more of a edge case maybe ? not sure
the docs just says
The null-conditional operator (?.) and the null-coalescing operator (??) are not supported with Unity Objects because they can't be overridden to treat detached objects objects the same as null. It's only safe to use those operators if the checked objects are guaranteed to never be in a detached state.
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Object.html
idk what detached state means tbh lol
destroyed basically
ah ok
What? No! 2026 is still in the insiders path. There's no way 2022 would be out of support. xD
anyway I'd rather use TryGetComponent when the component is on this object / not a parent / child
I guess it was the launcher that ended it's support? now that i remember
yeah like there's 2 nulls with unity, yeah?
actual reference null, or a destroyed Object
== null checks for both
is null/??/?. would only check for the former
so i think it'd technically work fine. probably still not good practice though
i don't think so
https://visualstudio.microsoft.com/downloads/
if you cache the result, destroy the object, then check with ?. thats when it will give errors. so you can use it safely but theres just no point in mixing it between using that and checking for null properly
gotcha
What launcher? Oh, I guess it's not just insiders anymore. But I don't think 2022 is out of support.
Though, I don't see it's download...🤔
Man... 2022 was so clean. Now third of the time i don't even have errors showing up in my code or randomly because unity and vs glitches, all my scripts lists are erased and i have to find them all again
i want to say is T t does also work for both? or am i wrong
oh actually it is still downloadable from https://visualstudio.microsoft.com/vs/older-downloads/
@teal viper @tender mirage
i don't think so. pattern matching wouldn't care that == is overloaded, it doesn't use == for that pattern
No way. Gotta find the time to download that. Thanks alot
I mean, we still have projects that use vs 2017 at work. Even if it's out of support, it's not a big deal.
yeah the is operator is still doing a pure null check like the null conditional operator
yeah there's this notice
Older versions require an active Visual Studio Subscription.
but 2022 isn't included in the following list
I wouldn't expect 2022 to go out of support for at least another year. it's supposed to get 5 years of regular support, then 5 years of extended support (which i think only enterprise gets access to?)
https://learn.microsoft.com/en-us/lifecycle/products/visual-studio-2022
seems to be till 2027
I hope by then they figure things out with 2026
Is it relatively new to have so many annoying bugs?
i mean, that's what the insiders program is basically for, to find all those bugs and squash them. make sure to report the ones you do fine
I bet it's just unity integration issue.
Honestly might be, but it's not prevalent nearly as much in the 2022 version.
Yeah, the ones i've noticed are pretty annoying like your whole script list getting deleted or errors stop showing up.
as well as the one most probably have experienced, when you create a new script it just doesn't automatically show up
in vs
if created in your ide it should work, otherwise unity has to update the ide project to include it
IsClient is false
This is again a #1390346492019212368 issue or you'll have to show how that variable is set
Curious does networking help with unity service specific problems
Wat
Unity cloud has service features such as player authentication and a leader board
It's not networking. You want #1390346533127458889
:O ty
for beginning work on my 2D top downs procedural generation what would be the best approach. It works by generating 1 - 10 different areas that the player will progress through and the entire thing is called a “Loop”. Should I use noise maps? Or by pre defined map parts
is this code related
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**
I am not getting any errors but the object is not becoming inactive, I checked "is trigger" please help
you have a typo, it should be OnTriggerEnter, not OnTriggerEmter
sorry, I forgot to tag you
What is OnTriggerEmter? What calls it?
thank you but it's still not working
Ok, do the colliding objects have rigidbodies with the 'isKinematic' unchecked?
the tutorial I followed removed the rigindbodies
the invisible box holds up other boxes then the trigger makes them drop
So, I believe you need to enable some settings now. If the bodies do not have rigidbody, then they will not interact by default. You need to go to:
Edit -> Project Settings, then select tab Settings under the Physics
then in the game object tab change the contact pairs to all contact pairs:
How do I rotate the Z angle of a 2D game object to the surface of another object?
Don't cross-post. You're already getting answers in the thread https://discord.com/channels/489222168727519232/1437915071626870804
where do i ask scene related questions? (dont see a channel for it)
yes
I am having a bit of trouble understanding the state machine are there any videos someone could recommend to make me understand how I could scale, transition, between states and how root states are defined, etc...?
Which state machine?
I was taking a look at hierarchical state machines.
Just conceptually? Or are you referring to some specific library or framework?
conceptually I can't quite grasp it
I'm not exactly sure what you meant by "scale" in your original question
when you are adding new states say attack or parry I don't get how people expand the scale of the hsm.
Just by adding states aren't you expanding the scale of the state machine?
I just realized what I said let me rephrase, I don't understand how people know what root states are as opposed to child states. How do I figure that out when expanding the scale of the hsm?
It can be complicated and it might not always fit into a clean hierarchy. But basically if you can do a thing while doing other things, that points to probably a child state.
For example "shooting" might be something you can do while walking, jumping, or crouching
Oh that makes a lot of sense actually, so would something like say a heavy attack where you are locked into an animation and can't move would that just be it's own state and not a children where you would transition from something like a move state -> attack state?
A lot of my ScriptableObjects have Name and Description field.
What is a common way of reusing that piece of code for all SOs that need these fields?
Should I just create ScriptableObjectNameAndDescription : ScriptableObject class?
Or maybe a struct/regular class that can be attached to it(but then you have to go through extra layer to get name/description.
You can use an abstract base class if you want
or a struct or class that you add as a field to them all
I will say that name exists on ScriptableObject itself already
(actually it comes from UnityEngine.Object)
I use uppercase Name field so I can name my weapons, enemies, spells etc
lowercase name is for asset file name afaik(or object name in case of monobehaviors I think)
hey folks. I have a player gameobject, I have chunk prefabs, and I have a chunk manager that I want to contain the scripts for spawning the next (adjacent) chunks as my player moves into them. I've followed these instructions (with debug.log to make sure that a triggering part works successfully, it does) but I'm unable to get the chunk prefab linked to the chunk manager in the inspector. I suspect it's a matter of trying to reference a gameobject on a prefab. I encountered this issue before but i can't remember how i made it work and im struggling to understand the fixes that google is suggesting. I'll send the screenshots of the instructions google ai gave me
it's the second point in step #4 that is the issue, dragging the ChunkManager gameobject into the Chunk Manager field in the inspector doesn't work because the chunk is a prefab
You should be able to drag prefab to a game object field
You should share your actual setup if you expect help. Very few people will engage in anything AI generated.
Plus at the end you seem aware of the underlying problem in the AIs suggestion, so there isnt much to say other than yes you cannot reference a scene obj from a prefab
If youre trying to reference the prefab from the in scene object, that works fine. It sounds like youre trying to do the opposite though
Wait a second, but where is scene in that? Chunk Manager seem to be a script on the game object in the scene and the chunk is a prefab, right? Or what am I not understanding?
i'll grab screenshots of my actual code
And also please make a screenshot in Unity
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Follow the bot command linked above
player, chunk manager, and then the chunks themselves which are prefabs
the chunk itself is whats looking for the trigger event
and i want that to communicate to the chunk manager object which handles spawning new chunks
im able to instantiate the first chunk just fine, because that happens at game start
the issue is getting the next ones to spawn as i go
but the reference you sent a photo of is not of type game object
it is on script ChunkBoundary and requires Chunk Manager
yeah thats where im getting confused. in screenshot 2 you'll see where that field is made. google told me to do "public ChunkManager chunkManager" instead of "public GameObject chunkManager". so I changed it to GameObject, but then it said that gameobject doesn't have the method spawnNewChunk
so i have no idea what to do
Oh, you will have hard time making a game because it looks like you are missign fundamental knowledge.
you need to get a component from game object by doing chunkManager.GetComponent<ChunkManager>();
Don't focus on what AI is telling you. All you need is a reference to chunk manager. It seems like chunk manager is already spawning the individual chunks.. so just pass the reference. Don't reference it by type GameObject, use ChunkBoundary
He doesnt have a reference to the object in the first place because its a prefab while the manager is in scene
Otherwise he could just directly reference the component
yeah, you are right
ohhhhhh wait, so I understand now. You are having a prefab that has a field and you want to drag an object you have in scene to that prefab?
yes
and i understand that that
isn't how it should be done, google is telling me to reference it at runtime
but im confused as to how to do this
Ok, you won't be able to do that. Instead of reference, if you want to do it dirty but quick, instead of using reference do FindFirstObjectOfType
Ive told you how above
#💻┃code-beginner message
If a specific step confuses you then ask about it
@eternal needle, what's wrong with my answer?
Its just unnecessary
Theres no world where you need to use the find functions here
I am an idiot haha, I just realized there is even simpler way, you are right
Can't you just set the reference in the script when you instantiate the prefab?
So your spawnNewChunk would have
var chunkObject = Instantiate(...);
chunkObject.GetComponent<ChunkBoundary>().chunkManager = this;
That is exactly what my suggestion is
sorry, it's already past 1am for me haha and I am not thinking straight 🤣
Except you dont need to get component if you reference it as type ChunkBoundary, which is what I said above
oh instantiate will return you a specific script? I didn't know that, I thought it always returns game object!
I just learnt something interesting than, thanks! :)
ok so the issue lies in the script on the Chunk Manager and not the script on the Chunk Boundary?
ill try that
There are ways to get/provide the reference from either script. This is just the simplest way considering you already have a list of the chunks
You just need to make sure that all chunks are spawned using this chunk manager, so the chunk manager can always provide the reference
is there a way to get a pointer to a unity.object?
hmm, still not working. Sorry if this is frustrating.
In what context? C# uses references, not pointers.
but there is an underlying native object that is created behind the scenes. Is it possible to grab it?
For what purpose?
What's the end goal?
Its a long story that is outside of the scope of this channel, is it possible?
To summarize it would prevent me from having to track gameobjects via something like an ID in my end user scripting language.
Can you just use the instance id?
so if I go from GameObject -> instance id can I go back?
only in the editor as far as I am aware
Again, youd need to show the actual setup. This doesnt give us any indication as to whats not working. If youre just relying on AI, maybe take a step back and go learn c# fundamentals or do the unity learn courses
If it's for an in game scripting engine I would just keep a Dictionary<int, GameObject> internally
There's this but I don't think it's a good idea to use: https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Unity.Collections.LowLevel.Unsafe.UnsafeUtility.AddressOf.html
IDK if it's stable or safe
It will be stable and safe as long as you dont attempt to access memory that is no longer allocated.
I'm not even sure then - what if the garbage collector moves objects around in memory
Unitys GC doesn't move items
its non compacting
wouldn't references go stale if items moved around after a gc sweep?
not if the references are also updated by the GC
these seem like GC implementation details
hence why I wouldn't personally mess with this stuff if I didn't need to
Seems like a Dictionary would be a much better/safer bet to me
might be my only option as awful as it is.
public unsafe static void* AddressOf<T>(ref T output) where T : struct
i got it working by passing the reference at runtime like google suggested because i couldn't figure out how to apply your solution in my use case. I've been trying to learn by doing, as back when I learned C++ i made very little progress by reading and only made progress when i decided to just jump in and fix problems as they came up. Most problems in unity and C# I have been able to learn from so far, but this solution still puzzles me so i'm going to go ahead and hit up the unity learn courses like you suggest before I continue on this game. I appreciate the help.
im not sure what google suggested but really the solution i suggested is like a 3 line change. You change type GameObject to ChunkBoundary, then cache the result of instantiate which would now return the component ChunkBoundary. Assign the chunkManager now that you have the reference
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thats the learn site though
fellas how can i do that if my bool like CanBeDestroyed is Checked it does shows a lot of options and configuration vars, but in case of CanBeDestroyed is false it doesnt show nothing like unable it
Is this some serialized bool
Custom editor script, or a plugin like : https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
If you can't be too bothered with plugins, just make some serialized class and stick the bool at the top of it.
Making a serialized class will collapse the rest of the params
ahh ok
Another idea is use a scriptable object and instead of checking the bool you can just check if the variable that contains the SO is null or not
I am having a lot of issues with my code if anyone is willing to help please let me know 😭
!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 #🌱┃start-here
particularly the last point, don't ask to ask
oh sorry, thank you!
So, one of my university projects is to reimagine an existing 2d game so i chose undertale, but I'm having this issue where the paper bullet here is supposed to follow the soul whenever it moves, but it doesn't. It instead only follows the soul's spawn position, not the soul itself. I've tried to fix this for days and can't figure it out
this code snippet is like 1 of 10 i tried, all to no avail 😭
props for using quaternions in 2D ;p
WAIT DOES THAT NOT WORK??? 😭 every single thing i looked up used it for this
I'd debug the position of this target to make sure it's actually moving, otherwise perhaps what you're targeting is not what you're expecting
yeah make sure your target is the actual scene object and not a prefab
so it IS a prefab and i did think that'd be an issue and tried to fix it but it doesn't let me drag it into the inspector unless it's a prefab
also yeah this helps cause it doesn't update it when i move the player so target is wrong somehow
you need to pass the reference when you Instantiate the projectile
https://unity.huh.how/references/prefabs-referencing-components
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
okay i skimmed through this a bit and maybe it's because im running on 3 hours of sleep but i dont quite understand?
you need to be referencing the object that is in the scene, not the prefab. but because prefabs cannot reference scene objects, you cannot assign the scene object to your projectile prefab. so you simply need to pass the reference to the projectile from whatever spawns it
OH PROPS i thought this said "probs"
what you have there looks fine? Usually people just use eulers (which is fine for 2D)
i had a euler but it got lost in the 15 code snippets i tried to use to fix this lmao
okay JUST to make sure im understanding, in my situation, would _prefab in this example be the paper or the soul (heart, the target the paper is supposed to follow)
oh wait
im dumb
disregard!
you can also use Quaternion.LookRotation and ditch atan2 if you wanted too I believe
nah, that points the Z axis at the target which is not ideal in 2d
if you specify up as vector3.forward, wouldnt that work, no?
seems like FromToRotation may be the better option here
I do recall getting angle axis to work like this before and it worked out
okay so i followed what the website said but nothing has seemed to change?
at least i think i followed it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
both the spawner and the other component im assuming?
yes
Ah, ok yeah you're right. LookRotation does only look at the z, I thought here was some additional params to change the forward but seems stictly to point towards the z
public BulletPathing gradePaperPrefab;
public Transform _target;
public float xMin = -7;
public float xMax = 7;
public float yMin = -4;
public float yMax = 4;
void OnEnable()
{
Vector2 spawnPos = GetRandomOutsidePosition();
Vector2 soulSpawnPos = new Vector2(0, -3);
BulletPathing instance = Instantiate(gradePaperPrefab, spawnPos, Quaternion.identity);
instance.Initialise(_target);
}
this is my spawner
hold on lemme get the other my computer is screwed up rn
also ignore "OnEnable" we were trying something and it technically works but we'll change it
public Transform _target;
public float rotationSpeed;
void Update()
{
switch (attackType)
{
case AttackType.GradePaper:
if (_target != null)
{
Vector2 dir = (Vector2)_target.transform.position - (Vector2)transform.position;
dir.Normalize();
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
Quaternion targetRotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
Debug.Log("Target position:" + _target.transform.position);
}
break;
}
}
public void Initialise(Transform target)
{
_target = target;
}
that SHOULD be everything relevant to this attack's behaviour (the paper)
so provided your spawner object is referencing the in-scene target in its _target variable that should work
oh i MAY be dumb i accidentally just filled it with the prefab again i NEED to get some sleep
it works now
thank you so much!
bookmarking that website that's actually so clutch
Vector3 direction = target.position - transform.position;
Quaternion targetRotation = Quaternion.FromToRotation(Vector3.right, direction.normalized); //Or is it transform.right?
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);```
Think that should be fine? Need to do a 2D project again one of these days
yeah now that i found out what the issue is im gonna tweak that part of the code to be much more simplistic cause there are simpler ways i was just spiraling LMAO
Like I said what you are doing looks fine. I'm just seeing what else works besides abusing eulers ;p
yeah lmao there were simpler code snippets that probably work out, that one issue probably screwed ALL of them up
i'll go back to my og one which was just a few lines lmao
I purposely typed a code wrong to check if it's working at all on an object and there were no errors. It is ignoring all my scripts, please help
code say "please open a folder with a solution to debug" if that helps
have you opened the project folder?
one script is showing errors the other isn't at all
what errors
sorry I mean one is working because it's showing errors the other is not showing any errors in console. My problem is the one not showing any errors because that means it's not working at all
nothing now I fixed it I added an error on purpose to check if both aren't working
Never mind it's working I don't know what I even did but now both are showing
I just kept messing with ui
Hey im following a tutorial for 3d movement and i seem to have got some weird error, the error says i cant do this with a bool, however the video im following those the exact same operation
video with time stamp:https://youtu.be/PIFQbxMgT0c?t=979
In part 2 of this series, we go through animations for running, sprinting and idling states. Additionally, we make a basic enum state machine to keep track of our player's movement state.
In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topi...
can anyone help me with this?
11-11 16:57:04.852 12351 19014 E Unity : DllNotFoundException: Unable to load DLL 'native-googlesignin'. Tried the load the following dynamic libraries: Unable to load dynamic library 'native-googlesignin' because of 'Failed to open the requested dynamic library (0x06000000) dlerror() = dlopen failed: library "native-googlesignin" not found 11-11 16:57:04.852 12351 19014 E Unity : at Google.Impl.GoogleSignInImpl.GoogleSignIn_Create (System.IntPtr data) [0x00000] in <00000000000000000000000000000000>:0 11-11 16:57:04.852 12351 19014 E Unity : at Google.Impl.GoogleSignInImpl.. why I am getting this error in unity 6000.2.6f2 version , before it my google signing work fine
something is different
anyone have idea about this how can i solve in my Unity 6000.2.6f2 version ?
alright i guess im just blind then will give it more thourogh check then
It would help if you posted the actual error message as well . . .
it just says i cant run the operation on a bool, but after rewriting it it seems to be working
the syntax highlighting makes it pretty obvious imo
i mustve missed a capital letter
you missed the () on the method call
ah i see
no they are right
i blame the tutorial tbh
its meant to be the bool
i mean IsMovingLaterally() would also work
but yeah, a variable the same name as the method...
The tutorial uses the local variable, but you used the method instead . . .
I was just pointing out, it's best to send the actual error message. That way, we can deduce what happened more clearly . . .
does anyone maybe know why the for loop in enableInGameUI() doesn't actually loop through and disable the children in my slider?
Well what do you have in that list?
So i found out why My movement system wasn't responding to Horizontal and Vertical the right way
I think so at least
Active input handling was set to the new one
should I be using the new input handler? as someone who's new, there's a lot more for the old style by the looks of it
and it just seems confusing
you can currently use either
is the new one worth learning..?
the new is enabled by default now, and is "better"... but I think for beginners learning adds an extra layer of complextity
Yes, the new one is well worth learning.. at some point
you don't need to learn the entirety of the old one
but if you have like, other stuff working (movement and physics etc), you could try looking into this, for example
it's more flexibility at the cost of more complexity
but it's definitely worth it
because it was breaking a lot of my code to try and use, Like, I couldn't make a super simple movement system the way I thought I could, had to do a weird round about way
so.. pick it up once I have the basics down then?
"basics"
whatever that entails on my end
ok well, can I ask for an example of how the new system works and what it's purpose is? what is the flexibility?
the old system just had axes and buttons, retreived by name, right? (idk i didn't really get into it)
the new system focuses more on actions as the primary structure, and each action can have bindings (which can be changed at runtime) along with interactions or processors to modify the input or detect certain patterns
it's a lot more done by reference and using assets
i'm not sure my newbie brain fully comprehends that
I've heard it has more complexity, but is that complexity there to shorten the process overall?
while the old system may use something simple, this might be able to make something a bit more complex with the same amount of lines kinda deal?
i don't think it really shortens the process. there is some setup to do, just to configure stuff
there's a default asset that has some basic bindings though
i don't think an amount of lines is a good comparison
ok, maybe control then?
there's a part of it that exists outside code
i guess there's a part where setup is less in code and more in references/assets
There’s also some parts of configuration you just outright can’t do via code in the old one
maybe i'll get it more when my projects start getting a little more technically complex
I don't see much reason to use it currently, as it was screwing up how I was looking at the documentation, as well as just general tutorials, and I don't quite get how useful it is currently because it sounds like it's a step above the old system in terms of neediness?
I may have that all wrong
tiny brain doesn't get it
I got distracted and haven't read up a bit.. the old system is good for throwing in quick input.. I think the new will always take longer because it requires a bit more setup/ code. So it's worth knowing the old just for quickness in prototyping... and new for fully fledged projects
maybe I don't have it wrong then, because the way it's described there is for a more precise correction of system management.
while the old one has a simple movement system you can utilize, you lack some of the varying control that lets you fine tune it completely
the new one lets you fine tune it far more than before as well as iron out and tighten the code up.
rope versus metal wire kinda deal?
takes longer to make but is stronger and useful for heavier projects?
Input systems are nothing to do with movement, per se. They give you an input and then you take that info and do whatever you want with it.
The new input system has, I dunno the term.. different 'setups'? that allow you to swap quickly and easily between controls.
EG: if you were making something like battlefield, one input set would be for on foot, and you'd swap to a different input set when you get in a tank, or another different one for a helicopter.
With the old system that would be a ball ache to code
ahh, I think I get it, it makes the process smoother to some extent, things like switching weapon, switching camera types, switching out controls?
i heard somewhere it lets you select something by name specifically?
probably class?
it's still lightly confusing
that makes no sense to me
guess i'll cross that bridge when i get to it
which may be soon
one of my goals with this first project is to have a terrain switch, since the idea is to "travel between past and present"
or maybe that'll actually be super simple
switching control schemes?
i'm just.. kinda repeating back what I think I hear
i can't really comment, i never used the old system much
i don't really like magic strings
the old didn't have to use strings
Input.GeyKey(KeyCode.W)
but then you're hard coding instead
and then you'd have to do negatives yourself too
yes, 'tis why it's not very good and things like InControl/ ReWired exist
ive heard rebinding is something the new system does easily while the old system you'd have to make yourself?
yup
I think this is the correct term for the new system
I believe it's sort of similar to ReWired
oh shoot, there is a thing called "scheme" in the new system but it's not what i was referring to
at least, i don't think so.. i was thinking of like, switching action maps
yeah, that sounds right. I can see clearly in my head the code ActionMap
out of curiosity - how would you go about rebinding in the old system, briefly?
would it just be checking every keycode individually and binding them to, essentially, your own inputactions?
I dunno how you'd do it and allow the player to rebind freely.
But brainstorming the BF example above with set controls (needing to rebind between inf/veh) I think one of the better ways to do it would be to have a class per input type. InfentryInput TankInput HelicopterInput and swap between the active one .. maybe
inf/veh
what do you mean by this?
ah
I am trying to teach myself some gravity stuff and accidentally made an autobounce
not the intended goal, but, I am not displeased
so it turns out, bouncing WAS infact the right direction, I just needed to do -transform.up
instead of standard transform.up
I agree, you keep each sensitivity value held in a different variable and just pull from that when the player's state changes (i.e. in a tank, in a heli, on foot)
hey guys quick question, how do I make it so a rigid body is easily moved by an object it's connected to (using a joint) like it's nothing?
not the right channel
supposed to work if it has 0 mass but it's not possible to set rigid bodies' masses to 0 sadly
thank you
oh didn't see that mb xd
exactly, don't crosspost please
got a question regarding falling.
so, I got falling to work as intended, but now i'm running into the issue where the player can "glide" off a ledge, and I'd like to have a separate animation for falling that's noticable.
i'm kinda hoping (since i'm using an if else to check if the player isGrounded, and both if and else are returning the correct statements.) that I can use Else to stop player speed entirely until they qualify for "grounded", is that possible or do I have to learn how to use Raycast to figure this out?
what are you using to move?
that I can use Else to stop player speed entirely until they qualify for "grounded"
wouldn't this prevent air movement as well? or do you want to prevent that too?
well, the way I was hoping to use it was to actually just stop the player speed rather than their controls
and when the grounded is checked for true, they'd get their speed back
so no, it doesn't affect any of that, kind of a weird way to loop back without touching Horizontal and Vertical
the issue I'm running into is, I can't give the players speed back upon landing on ground
well, are you saving it?
yeah
wel
oh you meant the speed itself
kinda just now realized I was setting the speed permenantly
is there a way to only set speed temporarily?
that's a dumb question actually i think, i can just use floats to change the speed
you've lost me
im not psychic, i don't know the context of your code lol
you can send it if you're going to refer to it, sure
but mostly i don't really get what you're going for exactly
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
it's available in #🌱┃start-here btw
public class ThirdPersonMovement : MonoBehaviour
{
//movescript
public CharacterController controller;
public Transform cam;
public float speed;
public float originalSpeed = 6f;
public float fallSpeed = 0f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
public float DashSpeed = 0.5f;
//gravity script
public float gravity = -1;
float velocityY;
private void Start()
{
//cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
//movescript
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).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 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.LeftShift))
{
controller.Move(moveDir * speed * DashSpeed * Time.deltaTime);
}
}
//dash script
//gravityscript
velocityY += Time.deltaTime * gravity;
Vector3 velocity = -transform.up * gravity + Vector3.down * velocityY;
controller.Move(velocity * Time.deltaTime);
if (controller.isGrounded)
{
Debug.Log("grounded");
velocityY = 0f;
}
else Debug.Log("NotGrounded"); //want to stop speed and then reset it once isGrounded is true.
}
}
use the large code blocks section please
?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
...you summoned the bot just to get backticks?
so.. would I just paste the Link it makes for me, in here?
A tool for sharing your source code with the world!
so what exactly is the intended behavior
...while i'm falling, I want Speed (the players speed upon an input being pressed), to be reduced to 0, then when I am grounded, for that Speed to return back to it's original value, so the player does not move while falling, and can move while grounded.
i actually managed to figure it out
a bit proud of myself, a bit more simple than using raycast I think
btw, you shouldn't have multiple Move calls in the same frame
CC expects 1 move per frame/update
so for gravity, what should I use instead?
or, well, better question is, what would you change?
because it seems to work fine at the moment
but i'm always open to finding a way to make this easier
calculate a combined velocity and appliy that to Move at the end
Character Controller determines its collisions based on what it hits on the last Move call, which includes setting isGrounded. If you call Move multiple times, the first one's collisions are effectively ignored, since nothing will have the time to actually read that collision before it's overwritten.
The usual symptom of this is either never having isGrounded set at all, or having it rapidly oscillate between grounded and not every frame
huh
well, I haven't run into an issue with isGrounded yet
in fact, it works exactly as I intended it to, which for now, with my current skill level, is probably good enough
spending all night to try and figure something simple out is a lil exhausting, but at least this way i'll improve my general skill
For a status effect system would it be strange for the SO for each status effect to not actually have any methods but instead have a big script that manually checks for what the last added effect (SO) was, and then goes through a list of if statements to check what to do?
Ex.
if list[-1] == a, do this
if list[-1] == b, do this
And then just continuing. It feels highly inefficient but its all I can think of. Just one master script to handle all status effects
you can have methods on SOs if you want, sure.
Usually I just like to do a singleton for status effects as you'll usually be running coroutines which SOs cant do
It's usually a choice of a manager running those coroutines or if you like keeping it all independent then sticking those coroutines on those independent gameobjects
But if you do want to do like a single script for all effects, which is fine honestly, just make sure you map everything to some enum/dictionary so you can just do a 0(1) lookup to what's applied
Hey, what tools or systems do you currently use for procedural generation and or NPCs, and what’s the hardest part about making them feel intentional instead of random?
How do i fix this error
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
from just this small description, yes it does sound very strange. It'd be quite easy to solve this using inheritance and just implementing the logic on each specific SO type. Also -1 index syntax in c# is ^1
It being installed and it being configured are two different things
Make sure that there are no compile errors and that the file name and class name match
Unity doesnt care much for file name matching or not in unity 6
But should make sure that previous error has been fixed befofr you make another class
I'm just repeating the popup message they didn't read
Fair point 😂
there are no erorrs
Did you fix the previous one you had posted about seconds before?
(Nvm that was 40 minutes ago)
thats a different script this one doesn't even attach
Okay so then move on to the next few words
my Dictionary's key is a string. Isn't there a way to loop through it with a for loop?
Or do i have to make a brand new seperate list?
public void SellAllOres()
{
for (int i = playerInventory.oreInventory.Count; i > 0; i--)
{
}
//Update inventoryListText
UpdateInventoryListText();
}
Wonderful
Also if you're going to post code in-line at least remove all the egregious empty space
Thanks alot.
i edited it. No worries there. It's just that i've been trying to get it to work.
when I fix the suggested error i get more errors
although without literating knowledge it was impossible xD
So you do have errors
Which you could see underlined in red if you configured your IDE
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i mean the new errors have no suggested solutions so the suggested help code just made it worse
Are they showing as underlined in red in your IDE
no
then configure it as you've been told multiple times now
I mean It shows red when there's an error with red underline but right now there is no red underline the only error is in console that doesn't show ay solution
Well, you do have errors right now
are those underlined
Why not take another photo of the code ^w^
Cause the one up here shows it aint fucking configured
Not code...
Okay, more errors. Are. They. Underlined.
no
then configure your IDE
so you can actually see the errors in the code
and not just guess blindly at a solution for your spelling mistakes
which option of the 4 am i supposed to click I updated the app that did nothing, isn't it already installed
Whichever one applies to you
That was very insightful.
How did you find the exact topic i was looking for?
public void RemoveAllItems()
{
print(oreInventory.Keys.Count);
//Loop through inventory length
for (int i = oreInventory.Keys.Count - 1; i >= 0; i--)
{
//Gets the index of certain key
KeyValuePair<string, int> item = oreInventory.ElementAt(i);
print("ItemName: " + item.Key + "ItemAmount: " + item.Value);
}
}
It works exactly as i wanted it to be.
im not sure if you saw/didnt understand one of my messages previously #💻┃unity-talk message
but you can iterate through the collection of keys, still using foreach, to remove the elements from the dictionary. Works since you're no longer iterating over the actual dictionary, just a list of keys that the dictionary has
its easy to find the topics with google. "loop through dictionary c#"
compare that to the initial question you asked, all i did was cherry pick words out of it to use in a google search. plus adding c#
OOOh wait. Yeah i did mention that after remembering you initially bringing it up
I stated that idea here.
I got mostly unity forums that were unrelated when i tried a search like that.
Yo I need some help with my unity project if anyone got time please @ me
!ask @icy wigeon
: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 #🌱┃start-here
How to put a string here via code?
You should ask in #↕️┃editor-extensions
anybody know why visual studio code keeps autocompleting stuff when i dont want it to?
like im trying to type Time.deltaTime and it keeps autocompleting to TimeOnly whenever i type the .
My health bar stopped updating in game view, when i take damage it doesnt update, but it does update AFTER i stop play mode. Any ideas?
public Transform _target;
Rigidbody2D rb;
public float cinnamoSpeed;
public float gradeSpeed;
public float rotationSpeed;
private Vector2 direction;
public AttackType attackType;
public bool isCollided;
public float maxRotationSpeed;
public float rotationAcceleration;
public float followDuration = 2f;
public float destroyBoundary = 12f;
public float rotationModifier;
public bool blueAttack;
public bool orangeAttack;
public bool isFollowing;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Player player = collision.GetComponent<Player>();
if (player != null)
{
player.TakeDamage(15);
Debug.Log("Damage taken");
}
Debug.Log("Bullet has hit the player.");
Destroy(gameObject);
isCollided = true;
}
}
using UnityEngine;
using UnityEngine.UI;
public class HealthBehaviour : MonoBehaviour
{
public Slider slider;
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health)
{
slider.value = health;
}
void Start()
{
}
void Update()
{
}
}
Check that you are not adding extra using instructions that you are not using. It will widen autocomplete options.
Also make sure IDE is actually configured for Unity correctly.
thought id add this too
current health is assigned in script
the autocompletes appear to add extra usings
sometimes
ive seen it do it before
but its not doing it right now
Problem would be in player in TakeDamage, presumably. That's the only spot that might be talking to your health behaviour, or is not talking to it
using UnityEngine;
public class Player : MonoBehaviour
{
public int maxHealth = 5;
public int currentHealth;
public HealthBehaviour healthBehaviour;
void Start()
{
currentHealth = maxHealth;
healthBehaviour.SetMaxHealth(maxHealth);
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
healthBehaviour.SetHealth(currentHealth);
Debug.Log($"Player took {damage} damage! Current health: {currentHealth}");
if (currentHealth <= 0)
{
Debug.Log("Player is dead");
}
}
}
this is the code it's referencing
What is healthBehaviour set to
can i ask what you mean?
I mean what have you assigned the variable healthBehaviour to
it should be up here
Yeah, what did you drag in there
oh
Something in the scene? Or a prefab?
i had the prefab issue before and someone here helped me and i was able to fix it so im hoping it wouldn't be the same issue?
I don't know about what happened before, but in this case is it a prefab or a scene object?
but in this case it could be? it is a prefab i had to pull in there
cause it wouldn't let me pull a scene object in it
If it's a prefab then you're changing the values of the prefab. So the one in the scene is unaffected
I have an asset on the asset store, script asset.
I have built it on 2021, then 2022, now 6.2
What would be pipeline to export the project for each version?
Opening project in each version and then building and uploading is really a hassle
Is there a smarter way? or just pick one version and go with it?
Problem is, if its latest version of Unity, older versions cant import it into the project, if its older version of the package i dont know if newer can import it but they cant if there is higher already online
dont really know where to ask because there is only showcase for the asset store, info online is really limited
anyone can help me making fps movement with character controller i nearly try every tutorial i can find but it doesnt work what should i do?
You'll need to be more specific about what "doesn't work"
Yo can anyone send me a code for egg hatching?
Don't crosspost, you got your answer in #💻┃unity-talk
Srry didnt see that I apologize
i got it its because of the input system
good evening folks
this isn't a social chat / offtopic.
if you have a Unity question !ask
also this is a coding channel
: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 #🌱┃start-here
I'm trying to implement steam lobbies in my game
But I'm getting these error messages
This is the code
using UnityEngine;
using Mirror;
using Steamworks;
public class SteamLobby : MonoBehaviour
{
public GameObject hostButton = null; // Reference to Host Button
// Reference to Networkmanger Script
private NetworkManager networkManager;
protected CallBack<LobbyCreated_t> lobbyCreated;
protected CallBack<GameLobbyJoinRequested_t> gameLobbyJoinRequested;
protected CallBack<LobbyEnter_t> lobbyEntered;
private const string HostAddressKey = "HostAddress";
private void Start()
{
networkManager = GetComponent<networkManager>();
if (!SteamManager.Initialized)
{
Debug.LogError("Steam is not initialized.");
return;
}
lobbyCreated = CallBack<LobbyCreated_t>.Create(OnLobbyCreated);
gameLobbyJoinRequested = CallBack<GameLobbyJoinRequested_t>.Create(OnGameLobbyJoinRequested);
lobbyEntered = CallBack<LobbyEnter_t>.Create(OnLobbyEntered);
}
//Host Lobby
public void HostLobby()
{
hostButton.SetActive(false);
SteamMatchmaking.CreateLobby(ELobbyType.k_ELobbyTypePublic, networkManager.maxConnections);
}
//OnLobbyCreated
private void OnLobbyCreated(LobbyCreated_t callback)
{
if (callback.m_eResult != EResult.k_EResultOK)
{
hostButton.SetActive(true);
return;
}
networkManager.StartHost();
SteamMatchmaking.SetLobbyData(new CSteamID(callback.m_ulSteamIDLobby), HostAddressKey, SteamUser.GetSteamID().ToString());
}
//Lobby Join Request
private void OnGameLobbyJoinRequested(GameLobbyJoinRequested_t callback)
{
SteamMatchmaking.JoinLobby(callback.m_steamIDLobby);
}
//Lobby Entered
private void OnLobbyEntered(LobbyEnter_t callback)
{
if (NetworkServer.active)
{
return;
}
string hostAddress = SteamMatchmaking.GetLobbyData(new CSteamID(callback.m_ulSteamIDLobby), HostAddressKey);
networkManager.networkAddress = hostAddress;
networkManager.StartClient();
hostButton.SetActive(false);
}
}
Soz
Thanks!
Out of some minor curiousity, as a newbie, how hard would it be to learn inverse kinematics?
Depends what you mean by "learn IK". DO you mean "learn how to use an existing IK library?" not that hard if you have scripting and animation basics down
If you mean "learn how the math works and implement it yourself", pretty hard.
Hmm, might be worth learning the long way?
Anyone know any nifty ways to get off-main-thread stack traces to log to unity logs? I had an exception happening (I subscribed to an ad completion event while the app was backgrounded, which updated some text, which blew up textmeshpro) and never knew about it until.. way too late.
(I'm already doing Console.SetOut() to a text writer of my own making..)
so i have a simple script for moving an object smoothly
public Transform target;
public float speed = 10;
void Update()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}```is there something equivalent for rotating stuff?
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, speed * Time.deltaTime);
what type would targetRotation be?
Quaternion
same type transform.rotation is
If you want, you can even use the same trick you're using here for position
target.rotation
^ rotate towards the orientation some target object has
thats what i did
but if i wanted to give it a rotation value how would i do that?
that is vscode, not vs
hey so im wanting to detect when i click on a gameobject
and i saw stuff saying to use the function OnMouseDown
but that doesnt work but im not seeing how to do it with the new input system
IPointerDownHandler with the event system
You need:
- An Event System in the scene (Create -> UI -> Event System)
- A collider on the object (or a 2D collider)
- A PhysicsRaycaster on your camera (or the 2D version)
- Your MonoBehaviour script to implement the IPointerDownHandler interface
that seems a lot more complicated
It is a bit more complicated but it's better
It will interact properly with the UI
doesn't sound like a code issue
perhaps ask #1390346776804069396
this is the function idk if im missing something
void GenerateChunk(int chunkX, int chunkZ)
{
int size = 16;
List<Vector3> vertices = new List<Vector3>();
List<int> triangles = new List<int>();
List<Vector2> uvs = new List<Vector2>();
float[,,] density = TerrainDensity.GetDensity(size * size, new Vector3(chunkX * ChunkSize, 0, chunkZ * ChunkSize), 0.05f, worldHeight, seed);
GameObject ChunkObject = new GameObject("Chunk_" + chunkX + "_" + chunkZ);
ChunkObject.transform.parent = this.transform;
ChunkObject.transform.position = new Vector3(chunkX * ChunkSize, 0, chunkZ * ChunkSize);
MeshFilter MF = ChunkObject.AddComponent<MeshFilter>();
MeshRenderer MR = ChunkObject.AddComponent<MeshRenderer>();
MR.material = TerrainMat;
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
for (int z = 0; z < size; z++)
{
float[] cube = new float[8];
for (int i = 0; i < 8; i++)
{
Vector3Int corner = MarchingCubes.Corners[i];
cube[i] = density[x + corner.x, y + corner.y, z + corner.z];
}
MarchCube(new Vector3(x, y, z), cube, vertices, triangles);
}
}
}
print($"Chunk mesh has {vertices.Count} verts and {triangles.Count/3} triangles");
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
MF.mesh = mesh;
ActiveChunks.Add(Vector2Int.RoundToInt(new Vector2(chunkX, chunkZ)));
}
your shader probably has issues, not your mesh
i cant figure out whats wrong with it im gonna crash out
i just created an empty Canvas and it happens
not a code issue - that's an internal editor error, try restarting
Alright
how hard is it to make a small multiplayer?
quite a subjective measure, but apparently it's relatively harder than.. a lot of other stuff
then i am gonna elaborate
don't need to, the answer's not really gonna change
you need to attach a collider in order to make it work, or else the click won't register
@kindred dome Old monobehaviour mouse events do NOT work with the new input system
You should prefer an EventSystem + PhysicsRaycaster/Physics2DRaycaster + collider and the event system pointer event interfaces:
https://docs.unity3d.com/Packages/com.unity.ugui@2.0/api/UnityEngine.EventSystems.IPointerClickHandler.html
Hmmm didnt know that since i work mainly with the old one, thanks for the tip
Once you start using the IPointer events with event system you wont go back
I've used them once for some draggable UI component, worked well
Hello, I'm trying to make a pool game and wanted to try something different than using Unity Physics. I was thinking of using Physics.Simulate and Script mode and have the entire simulation play out in one frame and then interpolate it depending on the cached data.
I want it this way, because I figured if we send the cached data over the network then I wont have to worry about network sync issues that Photon Network sync comes with(like latency).
I just want to know if this actually possible or if someone has done something similar to this?
doesnt photon have its own physics
it does, but we are facing sync issues on low network devices
no wait, you mean PUN2 has its own physics?
photon fusion has deterministic rigidbodies
We're on PUN2 and are using PhotonRigidbodyView
Ah, I see. I know they have a discord around somewhere so it's probably better to ask in there
otherwise try #1390346492019212368
Ow, so the Physics.Simulate and script mode cant be used to simulate everything in one frame?
i know the code has a very obvious problem of "that's a game object, not an int" but does anyone understand what im trying to do?
how would i go about finding the index of menu, and then going back 1
it feels like it should be simple and fairly obvious but im just running a blank
Well, usually for loop is the idea when you deal with indexing, but otherwise declare some integer before the foreach and increment as you loop through it
use a for loop
there's not really a concept of "the thing before" with foreachs
you could keep the thing before as a variable if you want
also consider what should happen when it's the first element
if that a list there is .indexof(menu)
I would expect the photon docs cover all of this really. Unity's Rigidbodies don't sync well and because of that you're usually simulating everything on the host while giving a kinematic instance to everyone else.
But yes, I would expect you to advance to simulation yourself as the host then transmit the new positional data to the clients
if ur using a list to represent its index.. you can do what stalin mentioned.. just get the index of the element and use that to load the pref scene..
int currentIndex = menuManager.MenuList.IndexOf(menuManager.currentMenuSelected);
int targetIndex = currentIndex - 1;```
else i would ask *what* is a menu? does it even know what sceneIndex it is?
menu.index or menu.id -> w/e as long as its an integer
```cs
public class Menu : MonoBehaviour
{
public int id; // could also represent Scene build index
}
// could even auto-cache it in awake or something
id = SceneManager.GetActiveScene().buildIndex;
int prev = menuManager.currentMenuSelected.id - 1;
SceneManager.LoadScene(prev);```
i think im getting a grasp on how to do this but im probably going to be testing for a while
turns out this was harder than i expected it to be
but .indexof seems to be what i needed
i will do my best to break it
turns out this was harder than i expected it to be
ahh, the joys of game-dev 😄
[Package Manager Window] Error adding package: https://github.com/lexonegit/Unity-Twitch-Chat.git?path=/Unity-Twitch-Chat/Assets/Package.
Unable to add package [https://github.com/lexonegit/Unity-Twitch-Chat.git?path=/Unity-Twitch-Chat/Assets/Package]:
No 'git' executable was found. Please install Git on your system then restart Unity and Unity Hub
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
Is there a github app i have to install for me to add this package or is there a way to circumvent this? and if I do need the app would this still work if I build the project and send it to a user without the app?
Change foreach to for loop and use i to get the index. I recommend getting comfortable with for loops before jumping to helper methods.
Package manager wants to use git to pull from that repo. It won't be needed in a built project.
https://git-scm.com/ for git. I'm not sure if embedded git installs (common in git GUIs) would be detected out of the box.
kk thanks :)
git included with clients like sourcetree arent because they dont usually add to PATH
not a code issue, see #💻┃unity-talk
I got a code issue, my objects are kinda falling even when i make them static, and i dont understand cuz im new in unity
Show the code
ok
but i dont have any code i just have basic movement and i was trying to make my player hit a wall and stop but the wall moves and then it starts falling
Then how is it a code issue
Misconception that even though you do a lot of this in code. If it's specific to values done on the editor, yeah you'll want to take it to #💻┃unity-talk
#⚛️┃physics even
I'm recently changing to Unity and have been confused with how inheritance works there.
Say I make a Vehicle class with a name and a Honk() method.
If I want to make a Car, Bike, or Boat, what is the common approach in Unity?
a) Just make like a VehicleComponent and slap it onto an Empty GameObject
b) Actually inherit it by doing "public class Car : Vehicle"
c) Make the vehicle a prefab or scene.. and inherit that?
Still trying to wrap my head around Unity's best practices. I come from Godot btw.
you would likely be adding the car, bike, boat component to their own prefabs unless the base Vehicle has it's own functionality to move around. It depends how you want to go about it, you could even have one prefab and add the correct derived component at runtime but that's not specifically required
It's very similar to godot. The only big difference here is usually godot native classes do require you to inherit from their component class if you do want to modify them, and even though you can extend similarly in Unity, it's not a requirement. Well, it's a mix of only having one script per node as well compared to how you can stick multiple different scripts per gameobject in Unity. Example of a problem, having a scene object that can have either a static body or a character body -> you need to have a wrapper node as the root
Is there anything functionally different between Car, Bike, and Boat, or are they all variables you could set in the inspector?
If you can make the different vehicles using only public fields on a script, having one shared "vehicle" script should be enough
Composing different object out of more generic components is usually more powerful. The downside is you have to manage components a bit more though. So I would prefer option a
Right! So in Unity, scripts ARE components, meaning that you make a sub-component to extend it (like a VehicleComponent -> BikeComponent) and put it on the game object. While in Godot, game objects are classes, in Unity, game objects are just component-holders and the components ARE classes.
exactly
Awesome, I'll look into prefabs and components to figure out how to use them now, thanks :)
You can pretty much stick everything onto one gameobject if you wanted, but I like godot's idea of forcing you to branch out your hierarchy
much more clarity when you can see the components on the scene viewport
one large problem with that idea in unity is you do incur a cost of a transform even if you don't need one
(to be pedantic - components (in the inspector) are instances of classes, which exist inside scripts. but you have the right idea)
-# (also to complicate things, "component" can also refer to the class of the component. and people use all 3 pretty interchangably)
What do you mean by "incur a cost of a transform"?
gameobjects always have a transform
Hi, my sprint variable does not change when i press shift, i was using gitHub copilot to help me out, this is my code for it to change, and this is my input system
- have you confirmed that code is running
- how have you actually verified that the variable is not changing?
1: yes as i got more on the code and i can walk and activate the sprint through the engine, making me run
2: i have the sprint as public to change it, but i can also see if by pressing shift it changes or not
you need to verify with code, don't use the inspector because if it changes but then something else is changing it back you might not see that in the inspector. so add some logs to that method to actually verify that it's being called
makes sence
Also are you actually using OnSprint anywhere? Is it actually being called by the input system?
There's quite a few ways to assign that action as a callback to that button, which one are you using?
thats actually the part where i think i did it wrong as i dont know how to properly work with the input system so well
Do you have any other On___ input methods that you know are running properly?
So, see how those are assigned, and try to replicate that with OnSprint
Check this script, and any other components on the object
i think i cant actually cuz they are vectors and i think shift being a button kinda changes the way it should work
here
can you try printing something actually useful instead of a blank string
Yeah, they'd get different parameters, but you can still see how they're called
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i was going to do it dont wory
it is completing dont worry
including for Unity types? and error underlines? because i can see in that screenshot neither of those are happening
maybe not, what is completing is the github copilot and its preety usefull
let me show you
wait i think i know how to fix it
this is how you fix it: #💻┃code-beginner message
having a configured IDE is a requirement to get help with your code here. so stop whatever you are doing and go get that configured
im about to tweak ou everything dissapeared
did you close the file
no more nothing
