#💻┃code-beginner
1 messages · Page 651 of 1
I would do something like this:
float angle = 0;
float degreesPerSecond = 50;
float min = 135;
float max = 225;
bool goingUp = true;
void Update() {
float frameBudget = degreesPerSecond * Time.deltaTime;
while (frameBudget > 0.01f) {
float target = goingUp ? max : min;
float diff = Mathf.Abs(angle - target;
float toUse = Mathf.Min(frameBudget, diff);
if (toUse < frameBudget) goingUp = !goingUp;
angle = Mathf.MoveTowards(angle, target, toUse);
transform.rotation = Quaternion.Euler(0, angle, 0);
frameBudget -= toUse;
}
}```
sr is there somthing else beside couroutine, this would make me have to change the whole functions chain
I'm a bit lost trying to figure out how I would do this. I've got the Skill script as serializable, public fields and all that. But i'm not quite sure how i would add them to the PlayerData script through the inspector. Other than making an empty object with the Skill script for each one and adding those?
You make an object, attach the PlayerData script to it, and you will see the list in the inspector for the PlayerData script
Simply remove the Start method from the code you posted earlier
this still like ienumrator but change all with task right ?
and set it in the inspector instead
It's quite a bit more involved than coroutines and requires an almost total rework of how you call functions
But it is an alternative to coroutines
I gave you the easy one first
See i'm not sure what's meant by "set it in the inspector instead". the Player Skills ist is public already, i can add things via the inspector. i'm just.. not quite sure what to add XD
dang so still have to change the the whole function chain then
wdym by add things
you should see two fields
the int and the string field
whatever they're called
If you see a single reference field, that means Skill is actually a MonoBehaviour or ScirptableObject
which you said it wasn't
(i may have changed it to see what happened... lol my bad)
So, set them in the inspector instead of using Start
That works, thanks. Starts the object completely turned around at first but once it starts spinning it stays within the correct angles
you'd just need to set the initial value of angle and the min and max according to what you actually want
Ah I see
pfffft yea made Skill not a monobehaviour.. again. figured it out XD thanks folks
For some reason the spherecast is finding both of these despite the fact that it has the same radius as the gizmo which clearly shows they aren't touching...
your gizmo is only drawing in place, but your spherecast is being cast an infinite range
are you certain you don't want an overlapsphere instead?
oh ok thanks
Hello, do unity projects normally separate the cs scripts from 3d assets? I've been having no luck looking for this.
This seems like a good practice in my mind since I think git is meant to store code only, but I dunno if I should gitignore the assets since unity create some .meta files for them.
I'm new to Unity so I'm trying to learn how to manage my 1st project, the 3d assets might scale to a very large size later on. Thank you!
That's the idea unless you want to fess up some monies for git LFS
if it's a small project you can probably manage as there's effectively no limit on the size of your repo, but github will send you angry email if it gets too big
also pushes tend to fail if file sizes are larger than a gig
in the biz, they would use a more asset-friendly VCS like perforce or plastic (which you might be able to do for free?) and/or have an asset server which is its own thing and runs locally (but then you're re-inventing addressables which I'm not sure I'd suggest)
Thanks! glad I had the right concern. Are there any resources where I can learn more about these practices, or do people just learn as they go?
My team's project is currently pushing assets to the repo so we might need to restructure.
it looks like unity bought plastic and integrated it into their built in system, so maybe use that? https://unity.com/solutions/version-control
I will look into it. Thank you!
I want my 2D game cam to be further away, how?
Distance of an orthographic camera doesn't matter
what you want to change is the orthographic size.
It wont let me
what won't let you
I cant change the value
CInemachine camera, as I said
the main camera is controlled by the cinemachine camera if you're using cinemachine
(are you??)
yeah
then yes
oh here, cinemachine camrea lol
I see thx!
Is there a way for a script to detect whether or not a controller is connected?
Wait nvm I figured something else out
No I haven't, back to the original question
do you mean as an event, or just a one-time check?
also, old or new input system?
hey how do i fix my transform gizmo mocing away from my playerobject as i move him again
Is the object marked as static?
not that i know of
Maybe record a video of what it looks like, because it's not clear what's going on.
Switch the gizmo mode from center to pivot
rightio
i have this problem where my objects origin was on a empty game object then suddenly after i open the unity editor next day the origin of my game object went from the empty game object to the canvas that was a child of the empty game object
what seem to be the problem and the fix for it?
im trying to rotate a 2d gizmo but im not sure how to do it. ive found the matrix4x4.TRS function but thats used for 3d andi m not sure if i can use it to rotate 2d gizmos
You can, just use the Z axis of rotation
thanks
Maybe Gizmos.matrix = Matrix4x4.TRS(position, Quaternion.Euler(0, 0, angle), scale);
if i have
{
CrouchInput.Toggle => !_requestedCrouch,
CrouchInput.None => _requestedCrouch,
_ => _requestedCrouch
};```
how should I implement a toggle to swap between hold to crouch and toggle crouch?
Do I implement a _requestedCrouchToggle = input.CToggle switch variable to dictate?
Hey, guys! I want to get reference to my volume effects and I am really not sure how to do it. What I want specifically is to get a reference to my motion blur effect from volume component. I am using URP and I am trying to somehow get a reference to it but since its not a component I am not sure how to manually do it because its the only way to actually get a reference programmatically.
motionBlurEffect = mainCameraVolume.TryGetComponent<MotionBlur>(out var motionBlur) ? motionBlur : null;```
Thats what I have tried to do but really it isn't a way I think and I am not sure if this works fine. What about the volume the reference is taken for motion blur is the problem
they're not unity components
Volume is a unity component
it's more like mainCameraVolume.profile.TryGet<MotionBlur>(out var blur)
Motion blur is a volume override
Volume is but motionBlur is not
I just showed you the way
This?
I did this as well let me try again I think I forgot to use the var keywod
keyword
because I have seen error to this one as well
no you forgot to use .profile and .TryGet
those are the important parts
You have mainCameraVolume.TryGetComponent<MotionBlur>
Yes its new
before this
I have used maincamera.profile
and the code you send probasbly forgot the var
I can't speak to code you haven't shared
keyword
it's not necessary
you can use MotionBlur instead of var
var is just a convenience thing
it is identical to writing the actual type
you could do TryGet(MotionBlur blur)
motionBlurEffect = mainCameraVolume.profile.TryGet(out motionBlurEffect);
no
Thats what I did before
motionBlurEffect = someBool doesn't make sense
Do I have to just use an if statement
it's:
if (mainCameraVolume.profile.TryGet(out motionBlurEffect)) {
// we found it
}
else {
Debug.Log("There was no MotionBlur on the volume");
}```
the bool returned tells you if the effect was found or not
I can use a bool variable
and store the return value to it
and then check with if statement
sure, you can do what you like, as long as you follow the syntax rules of C#
Yes I just got confused. Anyway, thanks!
I have used to drag and drop to tell you the truth and I have never get references programmatically XD
would have to be out MotionBlur blur, no?
He just forgot
Yo chat
Does anyone know why it's problematic to instantiate new GameObjects in OnDestroy? It inconsistently makes said objects not clear on scene reload for some reason
yes
Because when you unload the scene it will call OnDestroy on everything in the scene as it cleans them up, and then suddenly it's adding new obejcts to a scene it's trying to clean up
Ive been looking for a way to make a. Crouch similar to repo
Ohh, that checks out
@wintry quarry I just figure it out that the issue wasn't only the variable I had declared but also the namespace I was using, which was the one that is used with old post processing system stack v2. So, instead of UnityEngine.Rendering.PostProcessing I should have used UnityEngine.Rendering.Universal because I am using URP instead of Built-in.
Ah yeah - that's a common error
It's an issue with how the model was exported. If you make it a prefab you should be able to adjust it but I'd just fix how it was exported. This is a code channel also.
guys how can i write here code?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
ty
If there's a lot use an external site and post the saved link back here.
Guys whats the best way of movement at coding? I used rb.linearVelocity but its not good for topdown 2d
float horizantal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(horizantal, vertical);
rb.linearVelocity = movement * speed;
Why is it not good?
There isn't any one way to do something. Maybe describe what isn't working as expected etc
My Character is sliding if i use rb.linearvelocity
and when i use addforce its even worse why?
Sliding? Have you tried GetAxisRaw instead?
The rigid body component was meant to simulate rigid body physics. If you're needing game physics, consider making it kinematic or finding other solutions online
Maybe also clarify what you mean by "sliding"?
The only sliding i can think of here would be caused by the default smoothing of GetAxis
its not about that
its just a number
Well, then there's an issue in your logic(somewhere else). The code should be setting velocity to 0 when there's no input.
im trying
So did you try GetAxisRaw or not
If you're assigning the value directly to the velocity as illustrated above, it would be the determining factor as to why your object isn't stopping immediately.
If there are other issues with the physics simulation/interaction, you'll have to provide more information.
oh i got it ty last 1 more question, should i use * time.deltatime at this code rb.linearVelocity = movement * speed;
Nope
speed is in m/s
velocity is in m/s
Time.deltaTime is in s/f (where f is frames)
if you multiply by deltaTime here you get m/f, which is not what the rigidbody wants
can u give me another example when we should use pls?
wdym i didnt get it
if you have a bar that you want to fill (let's say from 0 to 1) over 1 second, you would add deltaTime each frame for 1 second
and why not for rb, for getting the same speed over second
if we dont use rb, we use then time.DeltaTime for getting the same speed in 1 sec
because you're not doing anything over time there, you set the velocity straight to the rb in a single action; the rb handles it from there, it does deltaTime on its own
oh ok i got it ty
rb.velocity is already "units per second", so using delta time is not needed (and wrong)
Roughly speaking, multplying with deltatime adds the "per second" part to things
it turns "per second" into "per frame"
(but Rigidbody.velocity is already per second)
Well, 0.25 * deltaTime is not 0.25 per frame
It is 0.25 per second
Thats what i mean
yeah
ah we're thinking in opposite directions lol
what i meant was some quantity speed in m/s, turns into speed * deltaTime in m/f
hello, may i ask what is the usual solution to have the horizon line up with the water?
not a code question
i cant seem to find any option to have the skybox lower
oh
sorry ill ask in the other channel
and don't crosspost
Hey, guys! I got an error of stack overflow and I dont think I know what causing it. When I start the game so I am entering play mode the error occurs and the game is paused.
StackOverflowException: The requested operation caused a stack overflow. UnityEngine.Events.UnityEvent`1[T0].GetDelegate (UnityEngine.Events.UnityAction`1[T0] action) (at <2431722e3e3e41d78b6718bb39ab9111>:0) UnityEngine.Events.UnityEvent`1[T0].AddListener (UnityEngine.Events.UnityAction`1[T0] call) (at <2431722e3e3e41d78b6718bb39ab9111>:0) UnityEngine.UI.CoroutineTween.ColorTween.AddOnChangedCallback (UnityEngine.Events.UnityAction`1[T0] callback) (at
if you look at the full stack trace, do you see anything about your own code?
Give me a sec
Yes I see that I have two errors in two lines of my settings manager script. Let me inspect it probably know whats causing it.
@slender nymph I am working on settings by the way with player prefs etc. Do you have anything in mind what is causing the issue?
how could i possibly know if you haven't shown relevant code or even said where the issue is occurring?
I am working on motion blur setting, so I have made a toggle and trying to make it functional.
{
if (motionBlurToggle.isOn)
{
motionBlurToggle.isOn = inactive;
}
else
{
motionBlurToggle.isOn = active;
}
PlayerPrefs.SetInt("MotionBlurEffectValue", (motionBlur.active ? 1 : 0));
PlayerPrefs.SetInt("MotionBlurToggleValue", (motionBlurToggle.isOn ? 1 : 0));```
When I am commented out this method the error disappears
So, probably somewhere here because the lines are showing that the source of the issue is somewhere here
you are likely calling this method in the toggle's event which means when you set isOn it calls this method which then sets isOn which calls this method which then sets isOn which calls this method which then sets isOn and so on.
check the docs for the toggle class to see if there is a method or property you could use instead.
Probably thats it
can someone help me, i cant use " else if anymore and im confused
im on a new line and need to use else it but eveytime i try to type it it corrects too something else
it autocorrects to extendedlistservices
are you sure you are doing this immediately following an if statement or another else if?
no im not
then.. you can't use else
well that would obviously be why
else always comes after an if
no i mean i did use ig first
ok, show !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/, https://scriptbin.xyz/
📃 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.
its working now but something is still broken
broken how exactly?
"broken" doesn't give us any info
if it worked you wouldn't be here lol
working on it
is your ide perhaps not configured?
note the errant ;
yes i see it
that is your issue
possible mistaken emtpy statement
that is ending the else if statement. so the following block statement is unrelated which is why else if is not valid after it
im comepletely new to this so please bare with me
ohhhhh
so i need to remive it then?
remove
i seee i seeee
also that's not unity, this would be better suited for a general csharp/programming server
https://discord.gg/csharp
also yeah, this is a unity server. general c# questions belong on the c# server
thank you fellas im taking a course right now on C# and im having an extremely hard time understanding what this guy is saying
can one of you help me with one more thing?
is the question unity related?
is the question unity related because this is a unity server
This is not definitely a Unity related issue XD
can someone help me out? I'm trying to make a test vr game in unity and trying to make a code for teleporting to start when a block is touched but even if the code works it says failed to build
start by investigating the first error in the console when you build instead of just focusing on the one that tells you it failed
theres no errers in the code everythings fine
i said in the console
all it says is Assets\velocitymanager.cs(18,1): error CS1022: Type or namespace definition, or end-of-file expected
well that is certainly an error in the code
can i just send the code
See this #💻┃code-beginner message
am i just supposed to put the code there
ok jeez using UnityEngine;
public class TeleportOnTouch : MonoBehaviour
{
public Transform startPoint;
private void Start()
{
if (startPoint == null)
{
Debug.LogWarning("Start point is not assigned! Please assign it in the Inspector.");
}
}
private void TeleportToStart()
{
if (startPoint == null)
{
Debug.LogWarning("Start point is not assigned!");
return;
}
transform.position = startPoint.position;
transform.rotation = startPoint.rotation;
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("TeleportTrigger"))
{
TeleportToStart();
}
}
}\
!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/, https://scriptbin.xyz/
📃 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 were supposed to format it though
as per the bot message
so.. there's a \ at the end? or did you fatfinger that when hitting enter
Anyway this isn't even the right file
oh yeah LMAO
The error message tells you which file it is
This isn't the same file
Show velocitymanager
i dont think i have velocity manager
you have a file called velocitymanager.cs directly inside your Assets folder. what is the contents of that file
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class velocitymanager : MonoBehaviour
{Rigidbody _
// Start is called before the first frame update
void Start()
{
_rb - GetComponent<Rigidbody>()
if (Rigidbody)
}
_Rb.velocity vector3. right;
{
}
}
do you just not read the bot messages?
!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/, https://scriptbin.xyz/
📃 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.
that is. very far from valid code
well how do i fix it
yeah there are so many things wrong with that
i have no clue what it's even supposed to be
Shift+delete the file and start over with a configured !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
but anyways; you said there "weren't any errors in the code", so you most likely haven't configured your ide, see above
Start by learning the basics of C#:
https://dotnet.microsoft.com/en-us/learn/csharp
And configuring your IDE yes
i'm sure the IDE would show at least something in that code? like it's absolute nonsense code even for c# standards
c# standards are relatively high standards
If it's VSCode it might not even recognize that it is C#
this would not parse in js
In an unconfigured VSCode it wouldn't surprise me if it was like "Yeah pretty sure this is markdown text"
i meant like unconfigured IDE that assumes you're just writing C#
surprisingly does
I thought it'd get to like line 5 and just give up
well the last valid line is line 9
i think there's enough identifying features to deduce it
using, the : for inheritance, top level class
Pretty sure that the code is parsed in some kind of chunks anyway, not sequentially
also yes the game can still work even if a code is giving you errors
but you need to resolve these errors before you build the game
i broke my ide configuration testing this. i literally just opened a new file and pasted the script and lost c# intellisense
that's how bad it was
-# fixed itself after a restart tho
Does anyone happen to know why this wouldn't work? I'm trying to figure out how the input manager works with lots of trouble. Instead of moving like expected, I'm getting an error of "ArgumentException: Input Button Up is not setup", but when I have an "Up" setup in my input manager, unless the issue is something else? Here's my code:
private void Update()
{
//movement
if (Input.GetButtonDown("Up") && isGrounded)
{
rd.AddForce(Vector2.up * height, ForceMode2D.Impulse);
isGrounded = false;
}
if (Input.GetButtonDown("Right"))
{
rd.AddForce(Vector2.right * speed, ForceMode2D.Force);
}
if (Input.GetButtonDown("Left"))
{
rd.AddForce(Vector2.left * speed, ForceMode2D.Force);
}
}
make sure there is no white space in the button name in the input manager
There doesn't seem to be any
did you highlight the entire name in the input manager and make sure? (press ctrl+A)
Can you show the "Up" definition in the input manager?
That's not the Input Manager
This is an Input Actions Asset for the new input system
Then what's the input manager?
Your code is referencing the legacy Input manager
Edit -> Project Settings -> Input Manager
that is in the Project Settings and is used for the Input class. you should be using the input system since that is what you've configured
Do you want to use legacy input, or do you want to use this input map?
I didn't realize there was a legacy version, my bad. The newer one would be preferred
Then you'll have to rewrite your code
Is this the newer one?
Yes
My professor only has outdated slides. Is there a big difference in the code or..?
The new system is more complicated and there are multiple options for how to set it up.
The code is very different yes
The code also depends on which workflow you choose
because there are several
Here's a quick primer @stark ingot
https://learn.unity.com/tutorial/setting-up-the-input-system-u6
If you're just trying to make something functional, i recommend going with the legacy version
I'm trying to make player movement with this input system and that's literally it
Mostly because this project needs to be done by the end of the week and I don't have time for anything too complex
Then yea i recommend the legacy version
Is this the legacy input manager?
use the input manager if you want your code to be worse and rely on strings. use the input system if you want something that is more flexible and better
Thenb you should use the old system
This one is
are you just not aware of the difference between the words "input system" and "input manager" even when they are right there next to each other in your most recent screenshot?
I wasn't aware there were two different systems in the first place
you learn something new every day
okay but you're asking repetitive questions after you've already been informed of the difference
Tl;dr
Input manager is if you need something functional
Input system is if you want something good and permanent
Oh I see
The new one is better and probably best to learn and go with for a long term project
The project I'm currently working on is very short term, so I'll be sticking with the older input manager
how can i add a sprite to a SpriteRenderer via code, im trying to make circles visible after creating them with new GameObject
thanks :D
you should just instantiate prefabs
how can i do that?
Hello! Im still trying to get the hang of C# and Unity, so ive been working with a hodgepodge third person controller I converted from a guide and with a state machine. And while that works, Im having the classic problem ofa moving platform that moves up and down at a speed, and when the players on it, the platform falls faster than the gravity, causing a sort of "jitter". Ive been trying to figure this one out, I believe I am supposed to create either a collider to check if the player is on the platform and then modify the velocity, but im kinda lost. Ive tried a few methods but nothing seemed to work really well. Any advice here?
Relevant code: https://paste.mod.gg/ntqxvjdzdlod/3
A tool for sharing your source code with the world!
Yeah they're a pain. You can kinda get away with childing the character to the platform, but ultimately you do need to sync the velocity between the two units
Since you're using rigidbodies, you can use OnCollision methods to grab all colliders that the character is touching which can help you grab the values from the platform
So I would get the platform based off the onCollisionEnter, and then id do something on top of the movement to additionally add whatever the velocity is to the rigidbody on top of the current movement code, or something along the lines of that right?
Similarly, id have to do the same with the jumping too
You'd probably grab the current velocity of the platform and just add that to the player's velocity + the current input velocity of the player
using forces for the player though is a little tricky if that's how you're doing movement which I'm not entirely sure how to blend it that well together
Hi, I have a simple question that shouldn't rack the brains of those smarter than me. What alternatives are there to creating movement for a Rigidbody Character Controller. I have this issue where I can't add force to the player because I am constantly setting their velocity to a movement input. I'm trying to add an explosive that launches the player, but I can't due to this issue. Thanks!
ah gotcha, ill experiment with it, thank you!
Also, you got OnCollisionEnter or OnCollisionStay. For enter you'd do some sort of toggle and undo it via OnCollisionExit, or you can just use OnCollisionStay
And, if it's not consistent enough, then doing some sort of spherecast may be a better way to keep that collider information going
I mostly just use forces or setvelocity with non-kinematic rigidbodies, but ideally you shouldn't be setting velocity unless for sudden directional changes like a dash but for your example of an explosive seems like an alright scenario for that.
You can always just grab the current velocity that's been established from forces used then use that along with the explosive
Would I be better off using forces instead of directly setting the velocity of my Rigidbody for my player movement?
Depends what you're looking for. If you want drag, friction, and all that jazz that's applied to rigidbodies, then you want to use forces.
alright, thanks!
Also physics materials only apply to forces as a lot of these properties would be overriden by setting the velocity
It's there a way to reassign the references of a script you changed the name of?
This kind of stuff I mean
Under normal circumstances, if you rename it through Unity or through an IDE with the appropriate configuration plugin, the asset GUID of the script should still be the same so this shouldn't happen
I renamed with rename feauture by default on Visual Studio
Try renaming it through Unity first
it should work
Rider handles it properly too
I guess VS doesn't
It renamed the script automatically, but not on the rest of the of places
VS renames properly if configured for unity correctly
Yeah, that would be usefull, how do I do that?
!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
Does it show misc files instead of the assembly when you're editing scripts?
Take a screenshot of the VS window with a script open.
This thing on top u mean?
probably need to be more specific. the using statements?
Looks configured correctly.
What's the difference between these two?
oh there was a whole conversation behind this, my bad lol
The top one is deprecated I think.
those are different IDEs
Try updating the bottom one though.
The thing is, the script asset did update the name when chaging it on VS, just that it didn't pass the references to the objects that use it
So that's pretty weird
When you put the text editor cursor on the class name, hit F2, rename, and apply it, it should rename everything correctly.
Objects in unity don't reference by name,but by GUID(what Praetor mentioned), so the name shouldn't affect anything at all, as long as the corresponding metadata file contains the same ID.
Actually, F2 does nothing lol, I may not have any keybind configured on this
The metadata needs to have the same name as the script file though(this is what a configured ide guarantees).
Maybe Ctrl + r then🤔
Yeah, that's the window I used, it did not update
If you recompile a script that doesn't have a metadata file with the same name adjacent, then unity would create a new metadata file and thus new GUID, breaking the references.
It should update the meta file, do you perhaps have auto asset refresh disabled or something? 🤔
It would work even with auto refresh disabled.
The only other thing I can think of is maybe some write access rights issues or something locking the meta file during that time.
Well, I had not touched any of that, pretty sure it should have an attached metadata
It does of course. The question is whether VS succeeds at renaming it with the script file.
Should VS script automatically rename the script if I rename it on the editor?
Cause it happens quite often when renaming that I the window I am working on gets a missed reference when renaming and I have to open it anew from the editor
the file will be renamed but the class will not
because visual studio doesn't have info about that rename and it can no longer find the file you had open (because that file is now at a different path due to having a different name)
Well, this is absolutely freaking wild
Cause I just tested that with a sample script and it did update properly, but it does not with the original script I was trying to change
The only difference I may see is that the script is inside a prefab?????
Must be something locking the script meta file as I mentioned earlier
Open the script path in explorer. Do you see a meta file with the same name? Does it seem to be read only in the properties? What path is it in?
Should be fine?
Right click the meta file - properties
And take a screenshot
Nah, it's not on read only or anything like that
It's in spanish, so u have to trust me there lol
Mmmm, they are each just next to each other right? Should that be a problem?
No. I just want to make sure it's not in some weird path like one drive or users directory.
Not that I know about lol
I once also had an issue when renaming with VS. It couldve really just been a hiccup. I'd just try undoing your change if possible with version control and trying again if this isnt common for you
It would not work with the rest then
Well I gave the old name back and recovered the references but.... changing it to a new one does not work
🤷 🤷 🤷 🤷
Maybe rename it in unity first to be safe then. It should be fine in that case
Can you look at the files in explorer after renaming it? Are there 2 meta files(one with old name and one with new name)?
Nope, just one
This did the trick tho
Has anyone used Jetbrains Rider? What other IDE's are out there besides VS and VS Code that you would recommend?
Just want to try something different.
bit of a pointless question here... I'm trying to get a vector that is rotated 90 degrees to the right and 90 degrees to the left of the player input vector...
// Get a Vector3 to the right and left of the input direction. Vector3 inputRight = Quaternion.Euler(0, 90, 0) * new Vector3(pm.horizontalInput, 0f, pm.verticalInput).normalized; Vector3 inputLeft = new Vector3(pm.horizontalInput, 0f, pm.verticalInput).normalized * Quaternion.Euler(0, -90, 0);
The first line works, but if I switch the order in the second line it doesn't. Why is this?
The second case gives the error
Operator '*' cannot be applied to operands of type 'Vector3' and 'Quaternion'
the multiplication is only defined in the one way for Quaternion * Vector3, it must be in that order
Cause a quaternion, even with the euler, it's not a vector 3. However, I think u can multiply a vector3 by a vector4
I think that's a valid operation?
No wait, forget that, I am dumb
weird but I guess it is what it is
I assume in C# the resulting type when you multiply 2 different types together is just defined on a type by type basis then?
correct, the * operator overload for mutliplying a Quaternion and a Vector3 is declared in the Quaternion type
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Quaternion.cs#L97
and it is only defined in that one way
Mmmm, apparently makes no sense to mutiply a vector3 by a quaternion???
quatrernions are designed to use vector3s. vector3s are not designed to use quaternions
Since quaternion is a defined rotation, that can be modified by a vector, but a vector, altho can be a defined position, can also be direction to rotate the quaternion, but the other way around it's not possible?
Fuck, quaternions are complex
actually that makes sense since quaternions have a much more specific use I feel
its not a quternion thing it's a code responsibility thing afaik
quaternions have been the most confusing part of unity code since I got started 😅
thanks for the answers
you are overthinking them
like most people do
just think of them as a variable that holds a rotation
that's all you need to know - along with the fuinctions defined here: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.html
don't worry about what's inside
I just think about them at that arcane language unity and blender convert my old good eulers to actually work properly for a reason I will never understand
That's quaternions to me
Maybe I'm confused as to what you're saying, but just as a Vector3 can represent a position or a direction, a quaternion can represent either an orientation or a rotation.
The terms are a bit fraught of course, but there's parallels
So you when applying a quaternion to a vector, you would.... rotate the vector on the direction on that quaternion from the vector 0 as rotating point? That's the operation we would be doing there? Cause I otherwise I don't see how you could apply that
lol yeah I just started watching a video on quaternions in math and he started talking about multiplying trigonometric functions by imaginary numbers
watched unity's videos on it and they skipped explaining what they are straight to what you can actually do with them... suffice to say im perfectly fine with not knowing how these actually work
When multiplying Q*V you rotate V around the origin by Q
yep exactly. That's all you need
Doesn't seem to have many applications on unity, given that you can just do that with parenting, maybe that's there was no need to implement that
It's quite common to want to do some rotation math withouit having to rearrange GameObject hierarchies or move Transforms around in the world.
i may be overcomplicating things, but I'm using it to use it to get the equivalent of transform.right for the direction the player is moving the joystick
If I know I want to rotate something along an axis I would always have it attached to empty parent to mark that axis, but maybe that's just me
So... like snapping it to full right even for a small tap?
Rotation math isn't always just used to rotate an object around an axis
Quaternion.AngleAxis(-90, Vector3.up) * new Vector3(joyX, 0, joyY);
I believe
(I forget which direction you need to go when rotating around up, it might be inverted)
Why remember a handedness rule when you can just negate it every time you do something 
currently my input vector is normalized so it already does this, but I'm using it for a wall running script
in the tutorial I watched, wall detection is based on the camera angle, which works for first person but i'm trying to make a mario style game
Send a raycast left and right and detect walls nearby
This is what I ended up using
Vector3 inputRight = Quaternion.Euler(0, 90, 0) * (orientation.forward * pm.verticalInput + orientation.right * pm.horizontalInput).normalized;
wallRight = Physics.Raycast(transform.position, inputRight, out rightWallHit, wallCheckDistance, whatIsWall);
seems to be working well co far
I don't see the need of any quaternions there?
You can technically go real lazy mode with this one and do 2D perpendicular maths
If the y coord is 0
but then you lose some flexibility if you want to do other rotations later. Depends on the needs
o snap didnt know theres a perpendicular function for vector2 yea that would simplify things
You want the character to just literally run up a wall when jumping into one?
run parallel to the wall
Cause you could just get the normal of a raycast detecting the wall and lock the character in to move on that direction
although i do have a wall climbing script that does just that, but only if the player if facing the wall head on
A run over a walk mecahnic can be done in many ways, but on a 2D game I'd say messing with quaternions it's overkill
But hey, if it works, go ahead
its a 3d game
yeah it does the raycast to check if the wall is on the right or left, uses Vector3.cross on the normal of the hit to get the wall forward, then moves the player in the direction of the wall forward
And does your character actually rotates? Cause u could just make it seem like so with animtaions, without ever rotating any actual movable abject
I intend for him to. currently trying to get it to work. wouldn't the animation be relative to whatever direction the object is facing?
The animation is relative to whatever you make it relative to. You animate the objects and the parent of all them would be the point of reference
my character is currently just the default capsule with a hat and a mustache
wouldnt i need to rotate the parent object in this case then?
Yeah, u can wrap that on an empty, and then u rotate the capsule as an animation, the player movement would be on the parent, not the capsule
But, you can do it in many ways, so not follow my take
Ah gotcha, that's how it's currently set up. The rigidbody and movement scripts are on a parent object. All rotations are applied to the childed capsule. Was wondering why they did it this way in the tutorial.
guys, what is most modern way to do 3rd person movement now?
I see many solutions on YT tutorials
Now I use this:
using UnityEngine;
using UnityEngine.InputSystem;
public class Example : MonoBehaviour
{
Rigidbody m_Rigidbody;
public float m_Speed = 5f;
public float m_RotationSpeed = 50f;
private Vector3 direction;
void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
void Update()
{
InputAction input = InputSystem.actions.FindAction("Move");
Vector2 inputDir = input.ReadValue<Vector2>();
direction = new Vector3(inputDir.x, 0, inputDir.y);
}
void FixedUpdate()
{
m_Rigidbody.MovePosition(
m_Rigidbody.position + direction * Time.fixedDeltaTime * m_Speed
);
Quaternion targetRotation = Quaternion.LookRotation(m_Rigidbody.position + direction);
m_Rigidbody.MoveRotation(
Quaternion.Slerp(
m_Rigidbody.rotation, targetRotation, m_RotationSpeed * Time.fixedDeltaTime
)
);
}
}
and where do I need to add normalized ?
And should I use Slerp for MovePosition too?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
LookRotation expects a direction and not a position btw, so that part looks wrong at least
The moverotation code is pretty much wrong-lerp/slerp
https://unity.huh.how/lerp/wrong-lerp
Applying lerp so that it produces smooth, imperfect movement towards a target value.
why? I thought Input.GetAxis is legacy, and InputSystem.actions.FindAction("Move") is new one?
Yeah this is the new system, not sure why they said that
Anyway there's not really a "most modern way" to do movement. Every game has different needs and requirements and different movement styles
oh shoot i misread it sorry
Have you guys seen/used this pattern before?
Chatgpt gave it to me for simulating pseudo polymorphism for static variables
it's pretty similar to most "generic singleton" implementations floating around
I'm not sure that type constraint makes sense though 🤔
This is probably bullshit
This is a typical approach: https://blog.yarsalabs.com/using-singletons-in-unity/#creating-and-using-generic-singleton
Not trying to be an ass or anything but if your coming in here just to validate a chatgpt result you shouldn't be using chatgpt
the thing is that even in official learn site there is legacy code
Thats why I ask it here
I mean the point is that supposedly you could have: MovementSystem : SystemRoot<MovementSystem>, use SystemRoot to define shared behvaiors between systems, and also use SystemRoot<MovementSystem>.static variables for keeping track of initialized systems
then again I might be better off just having the service locator or containers manage all instances of each class, but I figured using a static - store like approach per class could make it easier
yeah this is pretty much the generic singleton pattern, just using the name "SystemRoot" instead of "Singleton" for whatever reason
Oh ok; yeah thats because I was initially asking about if static variables in dervied classes of my baseclass SystemRoot would use class state from the base or derived class
The type constraint is typical and normal, better than constraining to MonoBehaviour
e.g. from me: https://unity.huh.how/references/singletons#generic-implementation
they really ought to teach more about design patterns in school
is there a name for a pattern where your essentially managing a store of singletons?
That doesn't make sense to me
Sounds like DI to me
So like, lets say my server is running code for 10 players, and each player has a movement system class which can really be a singleton if it we were only considering that single player's state
well it's not a singleton then is it lol
no lol, ig not. I just mean like a static store of instances
Sounds like a singleton that holds a Dictionary of instances.
It just sounds like a singleton with another design pattern in it
There's nothing specific to statics in this context, that just comes down to how you wanna organise your references to game content
Ok, thanks guys
(for example, imo having global access to all the player movement systems directly would be weird, you'd probably have access to all the players who each have access to their respective movement controller)
mhm yeah. Well I'm thinking about doing this: a bunch of SystemRoot clases that are the "roots" of their repsective systems (movement, camera, audio, etc). They all are responsbile for fetching their own external dependencies from other systemRoot classes via a service locator, and then that service locator would provide a way of inputing a player id so you can access all the systems for a specific player. Everything would still technically be accessible in the service locator at once, but it would provide a neat way for the server to only get what it needs via a single id.
I might be ignorant when it comes to this but it feels abnormal to have those kinds of systems kinda separated like that? why have movement, camera and audio be global access points that requires a player id when you could just have the players be the access point who each have their relevant references
ah so just have the player act as the service locator?
Thats a better idea
for those player specific ones yeah
something like that plays to inheritance's advantages too since you will likely have the same kinds of systems on a variety of stuff
eg. audio on players, enemies, interative objects
Such an obvious and elegant solution, and yet I completely overlooked it because I started bottom up instead of top down
Going through the tutorial I am running into something I am not quite sure I understand
Type collectible2DType = Type.GetType("Collectible2D");
if (collectible2DType != null)
{
totalCollectibles += UnityEngine.Object.FindObjectsByType(collectible2DType, FindObjectsSortMode.None).Length;
}
I was curious how the UI in the 2D part of the tutorial worked. I looked at the script and it seems to run this code above, but I dont see or understand how GetType works, because the collectables aren't Tagged and i dont see anyway to set a custom Type
sorry to interrupt but ive been avoiding this and just doing everything but it but when i move my player to the next boundry i have set it looks like its moving but the camera itself isnt ? idk
It's literally just getting a type from a string. It has nothing to do with Unity
I have no idea why they are doing it this way, by the way
they could just do
UnityEngine.Object.FindObjectsByType(typeof(Collectible2D), FindObjectsSortMode.None).Length;```
whaat do you mean?
It's right there in the code
They are providing a literal string "Collectible2D"
presumably there is a script in the project called Collectible2D
it's a class name, yes
The preferred way to write this would just be:
totalCollectibles += UnityEngine.Object.FindObjectsByType<Collectible2D>(FindObjectsSortMode.None).Length;```
i have no idea why they did it that way
I guess so it would compile even if that script was deleted from the project
I guess more user friendly to display the use of variables and stuff to newer programmers
or that
public abstract class InspectorField<T> : InspectorField
{
public override bool TrySetTargetValue(BoxedValue potentialValue)
{
if (potentialValue is BoxedValue<T> castedValue)
{
SetTargetValue(castedValue);
return (true);
}
return (false);
}
}
I can do generic type checking like this right? where if the InspectorField<T> in question is a InspectorField<string> and the BoxedValue<T> is a BoxedValue<string> ?
Why not take a BoxedValue<T> as an argument directly?
the thing running this doesnt know
?? why isnt my camera moving
also consider showing screenshots of the component setup instead of making people watch your mouse wiggling video to figure out what might be wrong
i was about to do that..
Why its so laggy ?
PlayerMovement script:
using UnityEngine;
using UnityEngine.InputSystem;
public class Example : MonoBehaviour
{
Rigidbody m_Rigidbody;
public float m_Speed = 5f;
public float m_RotationSpeed = 50f;
private Vector3 direction;
void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
void Update()
{
InputAction input = InputSystem.actions.FindAction("Move");
Vector2 inputDir = input.ReadValue<Vector2>();
direction = new Vector3(inputDir.x, 0, inputDir.y).normalized;
}
void FixedUpdate()
{
if (direction != Vector3.zero)
{
m_Rigidbody.MovePosition(
m_Rigidbody.position + direction * Time.fixedDeltaTime * m_Speed
);
Quaternion targetRotation = Quaternion.LookRotation(direction);
m_Rigidbody.MoveRotation(
Quaternion.Slerp(
m_Rigidbody.rotation, targetRotation, m_RotationSpeed * Time.fixedDeltaTime
)
);
}
}
}
hierarchy
What do you mean by laggy
- the model shakes when moving on the cube
- the model sinks into the floor and then passes through it
see video above
!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/, https://scriptbin.xyz/
📃 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.
they posted the code
To answer your question tho, check the physics material
Wdym, is that not whats affecting it?
afaik physics materials won't cause that no
Oh i see
Im guessing the rotation is only considering 2 axises(is that the plural form) and thats whats causing the issue?
Also I enabled freeze rotation X+Z
And use these rigidbody settings
Using MovePosition is not great - it doesn't respect collisions. The jittering is likely from it moving inside the object and then being forced out by the physics engine violently de-overlapping them
what to use for 3rd person player then? What is the proper way?
there is no "proper" way - it depends on your requirements
you could try setting velocity directly
or using forces
the thing is - character controllers are actually complicated things. If you want something that is not just super basic, it's going to be more than 6 lines of code
got it, thanks. Will research then
Obligatory just get KCC from the asset store
Are you trying to make a rigidbody character controller?
like a character controller that sits inline with the physics engine?
As everyone else has said, you shouldn't be using MovePosition or setting the position of a rigidbody manually. This defeats the whole purpose of using a rigidbody.
You should be driving the rigidbody using .AddForce() calls or setting the velocity directly
If you use .MovePosition or .Position, you're forcefully bypassing the physics engine
You don't really need KCC. This stuff is pretty easy to do by hand.
Also if you want to make your rigidbody controller walk up slopes: easy, just project your movement vector onto the plane of the surface you want to walk on. Butter smooth movement.
probably) I am not sure how to name it properly
I found this one. Its the exactly what I need
https://assetstore.unity.com/packages/tools/physics/character-controller-pro-159150
what is KCC?
A pre-made character controller
ah
and what do you think about my hierarchy ? Is it ok?
I have empty parent "Player" with just rigidbody and script
With childrens: Collider (just empty gameobject with capsule collider), Capsule (I will switch it to player model in future)
Just make your topmost object the capsule with the collider and the script
all in 1
so just 1 gameobject? but if I will need to switch from capsule to player model?
On the topmost, you can do empty gameobject, collider, rigidbody, and your movement script (all on the empty gameobject)
then have a child be the visual representation
got it, thanks
I'm pretty tired so idk if thats the best way
someone else might come along to help you better
@somber radishjust make sure your child doesn't have a rigidbody or collider on it
it should probably just be purely visual, until you get everything working
I think its a proper way. We separate physics and visual part
Hey I was told to come here to learn coding so uh….what now?
Suhhh yes it is in the pins
how can i get my mouse position as a float, i tried using mousePosition and also putting it into a screentoviewportpoint
I need thoughts about this Prefab for our player character, is it too much crammed into one? what should I do otherwise
Our game is leaving prototpye stage so I want to do things properly moving forward, also this first game ever 🙂
Looks fine enough
I don’t have personal experience but from what I have read/been told etc. most games that ship end up having very cursed player setups
It's a vector not a float, but show what you tried?
It’s the hotspot of game dev arbitrariness that eventually just goes against good code and dev composure
this is what ive tried
also tried getting x and y in their own variables but that also didnt work for me
The issue is not with the vector, it's that if you pass a vector to Instantiate then you have to pass a rotation as well
so Instantiate(myPrefab, mousePos, Quaternion.identity);
oooh that works :D weird i cant just pass position
its because there is not an overload for Instantiate() with only these 2 arguments.
So you have to do (obj, pos, rot)
And this is by design because when you instantiate by position, we should also specify the rotation
what's the name of that one website with all the unity code terms and their applications
It says the errors are in PlayerMovement.cs
that would explain it
or the unity documentation?
If your errors aren't underlined in your ide you need to configure it !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
just downloaded https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131#reviews
After open scene, I see this
Why? all objects are pink in game mode too
the materials are probably using shaders from the wrong rendering system (e.g. built in but you are on URP)
you can try an auto upgrade via Edit > Rendering > Materials > Convert selected blah blah
select the material assets first...
e.g. go to mesh renderer, find material, select it + others, use menu item to auto update to URP shader
or, just use your own materials and not bother doing this
works! Thanks
new skill unlocked
I have two problems...
what does it mean by "Testing the Internet connection using Speedtest.net" and why its has an error
and "Running the UPM health check" i dont know what this is tbh, pls help me fix it.
cool terminal but I think that is to verify you have functioning internet
Any idea how i can fix it?
for more context I havent opened this project in a while(8months or so), is there something i might have missed
what unity version? could just be old and somehow the installation broke
hmm its " 2020.3.32f1 "
oh shit yea thats super old now, 2022 is the min with free updates
oh ok alr i try that out thanks
try unity 6 if you can and make sure you have a backup if you arent using source control
and can i ask these sort of question heere or is there an another channel
Noted thanks
can somone quickly vc for a quick bug fix. Its my fist time using unity and im strugaling to referance boolian from another script
you need to do thing.bool to access a variable from some class instance
e.g. if(JumboJoe.joeIsAlive)
no its to do anything with something else
you may need to read up on c# basics if this is stumping you
do what i did
yea im used to python and dbs and even then i only used python for a year or so
still a thing in python
public class MyClass
{
public bool myBool = true;
public int myInt = 5;
}
MyClass c = new();
if (c.myBool)
{
Debug.Log("myBool is true!");
}
if (c.myBool == true)
{
Debug.Log("myBool is true!");
}
if (c.myInt == 5)
{
Debug.Log("myInt is 5!");
}
im still confused as to why its not accepting ==
you wrote it wrong
the comparison should be INSIDE the brackets
but as i have demonstrated, a bool on its own is valid as it is gives a true or false result
true == true is redundant so we put just true
ive fixed it by removing the semi colon but i dont understand how that works
first of all, you need to configure your IDE
you dont add semicolons at the end of it statements
python user moment (not used to where they go)
thank you
go through that, then go through !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yea ive never done any game dev iv only used python for uis and data bases
yea basically all other languages use {} and ; due to being C like so its something you want to learn and understand!
yea i just wana pick it up as a hobby and make a dead cells spinn off kinda thing
Dude thanks, I updated it to a 2022 version and it works and looks fine, just some minor bugs(i think).
!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 followed it and it did nothign
you clearly don't have a configured ide there
configuring your ide won't fix the issue, but it's a prerequisite to get help here
go do so
are you using vscode?
visual studio
strange, i was using vs and didn't recognize that lol
i was going to say that vscode is trickier to set up
is it though
i remember having issues with it, which is why i changed to vs (though now im on rider)
but yea this is still a configuration error because none of the vector stuff is highlighted
the game development stuff is slected in the vs installer and it is setup here i think
isn't the "miscellaneous files" at the top there supposed to be the assembly
do you have the visual studio editor package installed?
snipping tooled it out
what...?
oh i misunderstood what you meant
quite strange, when you choose the external script editor there aren't any other choices?
this part
it was the only one
did you try restarting unity?
could also be an editor bug
just close down the project + your IDE and start it up again
also try regen project files
!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/, https://scriptbin.xyz/
📃 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 i got a little error in this script https://paste.mod.gg/brrqyvhbvwop/0
here is a script connected to it https://paste.mod.gg/ifcxsgptdlga/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
what's the error?
this
i created a node script, now i am trying to call it, its not functioning correctly for some reason, i keep getting errors
but what do the errors say?
that's where, not what
yeah that's the second one
and that's because you have 2 expressoins directly one after the other
you haven't put anything separating them
i didnt know where exactly to put em
screenshot of a example please
nope, not a screenshot
, just looked it up
didnt work
When you hover your mouse over the red squiggle underlines, it should give you some clues about what is wrong.
sure
then you put it in the wrong place
$"string content {valueFromOutside} more string content"
ah, my dumb ass tryna convert tring to a game object
makes it easier to read, but still, learn how to read errors and fix them
How do you make a first person camera with the new version of cinemachine 3.x?
I am noticing a lot of differences, either in how things are labeled or configured now
@acoustic belfry
If you're just looking on how to make a struct that's serializable with an ID that's editable in the inspector you can do something like this:
public class Dialogue: Monobehaviour
{
[Serializable]
public class DialogueContainer
{
public int ID;
[TextArea(5, 5)] public string Dialogue = "";
}
public List<DialogueContainer> DialogueContainers;
private Dictionary<int, string> dialogueDict = new();
private void Awake()
{
foreach (var container in DialogueContainers)
{
if (!dialogueDict.ContainsKey(container.ID))
{
dialogueDict.Add(container.ID, container.Dialogue);
}
}
}
public string GetDialogue(int ID)
{
return dialogueDict[ID];
}
}```
Problem with doing it all in the inspector is it could get pretty overwhelming if you're doing some large amount of dialogues
oh, interesting
btw how do i post codes?
i always forget the page
!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/, https://scriptbin.xyz/
📃 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.
thanks
btw this is the intro script (remember my dialogue script got deleted)
A tool for sharing your source code with the world!
the issue as seen, is that every line, is on it
Well, like I was saying I'd just use scriptable objects per dialogue, but hardcoding it like you're doing there is fine. I'd suggest using a dictionary instead of this large if statement though.
or atleast a switch
only reason I say scriptable objects over doing those container classes is unity's inspector gets slow af the more nested objects that are available
Oh
Having some trouble with UnityEvents...I have the following logic, when a timer finishes it invokes the event which calls a state transition on my "Game Pieces"
this.GetComponentInParent<GamePiece>().onPieceTimerFinished.Invoke();
Then on my GamePiece.cs itself I have
public UnityEvent onPieceTimerFinished;
void Awake()
{
onPieceTimerFinished.AddListener(delegate{SwitchState(moveForwardState);});
}
Now this works on a single gameObject, but I have multiple in play. Every time a timer is finished, the event is invoked on every single piece. How would I solve this?
Don't know how clear this is sorry
Huh, sorry for my ignorance but how do i do a dictionary or switch?
Oh wait, I'm supposed to use "RemoveListener" at some point, aren't I?
yes
Yea RemoveAllListeners() works for me here. 
Yo so this is the fastest fix ever but how do you put a picture (non UI) in 3D, in 2d I just drag it over but it doesn’t work here, I need it as reference for my terrain
Make a plane or quad and drag it onto that
actually may need to make a new material if it doesnt create one itself
You could also make a SpriteRenderer manually and assign the image to it
SpriteRenderers still work in 3D just fine, they're just flat
You might need to change your image type in the import settings from "Texture" to "Sprite" though
Maybe Canvas in world space would help here?
Hi!! Im trying to make a minigame for class but the teacher doesnt explain quite well unity programming, and I was looking online for some tutorials. To create a game where the player needs to grab balls and put them into a hole would it be very difficult?? Thankss
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!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/, https://scriptbin.xyz/
📃 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.
Hi friends! I'm using the following code in a private void update method to pause the game. It works perfectly fine, but when I change it to a fixedupdate it doesn't work. I don't think I need it to be in fixedupdate, I'm just really curious to understand why that would cause it not to work.
if (Input.GetKeyUp(KeyCode.Escape) && !isPaused)
{
Debug.Log("pause input registered");
isPaused = true;
Debug.Log(isPaused);
}
else if (Input.GetKeyUp(KeyCode.Escape) && isPaused)
{
isPaused = false;
Debug.Log(isPaused);
}
}
Input is read in update. GetKeyDown and GetKeyUp are true for only the exact frame you hit the button. They're set to true at the start of the update loop and false at the end. FixedUpdate is on its own timer, separate from the update loop, so those values are not true by the time fixed update rolls around
Oh okay, that makes sense. But I run my player's movement in fixedupdate and it's fine. I use code like this to move the player in fixedupdate
if (Input.GetKey(KeyCode.W) & !isMoving & !isDead && GameManager.isPaused == false)
{
north = true;
south = false;
east = false;
west = false;
StartCoroutine(MovePlayer(Vector2.up));
}
oh wait, GetKey must not be just one frame
GetKey is true the entire time a button is pressed
Oh cool. I get it. Thanks!
I made a rough setup of how my terrain should be, how do I smooth it out? the smooth tool makes it look weird an ddoesnt remove the bulky look
this is a code channel.
#⛰️┃terrain-3d
Hi! I'm having an issue and I am unsure if its my IED or if I am going crazy. I'm trying to have a timer display visually and I'm following a sort of tutorial about how to do it and when I added the Timer class, I think it added using system.threading which allows me to have a timer class. But when I try to find the object of the timer it says that system.threading cant communicate with UnityEngine. When I delete sytem.threading it no longer registers my Timer as a class? What do I do here? Am I doing something wrong? https://paste.mod.gg/rcixbmcyiwwe/0
A tool for sharing your source code with the world!
System.Threading.Timer is wholly unrelated to unity
it's not your timer, is it lol
and it's not unity's either
FindAnyObjectByType is only gonna work on components that unity knows how to work with
don't just type random stuff and expect it to work lol
try googling "unity timer" or something and see where that leads you
What's even the meainig of the Z position on a rectransform?
Isn't the sorting layer the thing in charge of determining what goes in front of what?
no clue but definitely not a code question, try #💻┃unity-talk maybe
It is, cause I am trying to move it with a corutine and I have no freaking clue if I should be using vector2 or vector3
I already have a timer set up is the thing. It functions too I can send that as well maybe I just have to redo the timer in a different way because the gdtv build theyre on was when visual studio code was still backed by unity. I was tryna figure out if I still needed system.threading but I can try doing some more deep diving
Nvm chat I found this issue it was a captial error and I feel like an idiot o7 thank you for the help!
does it really matter if you just want it to stay at 0 on the Z axis?
Yeah, cause I am not even sure what position I am looking for, it's anchoredPosition? rect.position? I am getting really confused....
huh? how is that even remotely relevant to the choice to use a Vector2 or Vector3?
is your actual question "what property am i looking at in the inspector?" rather than "what is the meaning of the z axis"?
Hi guys, I'm trying to get OnMouseDown() working when clicking on a sprite. I added a BoxCollider 2D, and the game still doesn't recognize my clicks. Does anyone have any ideas?
for starters you need to get vs code configured 👇 !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
and secondly, if you are using the input system you should be using the event system interfaces like IPointerDownHandler rather than OnMouseDown
Cause it always shows on the rectTransfrom component as parameter, which is not the case for the X and Y components of the vector3? So I am not even sure some recttrasnform even have a position determined by a vector3, thus me asking what the heck is going in here
RectTransform inherits from Transform so it is inheriting the Position property which is a Vector3. so it has a z axis.
that's it. it's no more complicated than that.
I tried something like this. It still doesn't seem to work. Did I use the right syntax?
have you configured vs code yet? it is a requirement to have it configured in order to get help here
that is not configured
does anyone have any ideas with up with enemyList not showing up in the editor?
- Have you saved
- Do you have any compile errors
everything else just works fine but enemyList is just poof
no compilation errors and i did save
have you done something silly like disable the automatic asset refresh?
Try making a change to the code, saving, then going back into Unity and see if it re-compiles everything
by chance, if i did, how would i check that
well you can press ctrl+R in the editor to trigger a refresh, but it would also be in the editor preferences
if all else fails, try selecting some other gameobject and then reselecting the one you've shown
ive gotten a graphical bug where some fields just don't show up randomly
going to try all 3
wha
WHERE
oh its a script thats not attached to anything and hasnt been used
hooray you have compile errors and probably turned off the automatic refresh
i wasnt getting an error before because it was closed down and has been closed down for who knows how long 
just going to delete it. it no longer serves a purpose
🙏
Doesn't matter, if it's in the project, it stops all compilation on error
wdym "it was closed down"? any error would show up in your console even if the script is closed, provided it actually attempted to compile.
i need to start cleaning up my files 
i was testing different ways to have random enemies spawn in any given room but i wasnt sure whether to put it in another script, or give its own exclusive script. unfortunately giving it its own script would have just made it messier
also just FYI, you really shouldn't make every variable a GameObject type, you almost never need that. You should be using the type of component you actually care about instead.
hey yall, so dealing with a bit of a nightmare situation with some code logic
so this is the current flow our game goes through in order to respawn a player:
-> Case: Die in gamemanager.cs is triggered
-> which starts monster kill animation in monster.cs & starts player death animation in playerstatus.cs
-> Monster kill animation triggers animation event, where monster.cs restart() is called
-> monster.cs restart() triggers gamemanager's case: ResetLevel
-> Case: ResetLevel calls Room.cs respawn()
-> Room.cs respawn() calls player teleportation
so this isn't designed by me, I'm looking to fix this as the logic is way too tightly coupled, however what's a good option to solve this?
using unity events?
Hard to know the details, but the obvious first easy reorg would be to move all of the game-wide changes out of monster and player classes. Seems like it would work much more cleanly in gamemanager.
The monster/player can tell the manager it needs to die, but the manager can then... manage what happens with that request.
game-wide changes being something like the monster's position?
why does the player dying trigger a monster kill animation?
monster killing the player, first person game
what is it? this is an animation on the monster?
yep
wouldn't whatever animation the monster is playing which did damage to trigger Die already be playing?
public void restart()
{
monsterCollider.enabled = false;
animator.SetBool("Kill", false);
rb.constraints = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotation;
transform.rotation= Quaternion.Euler(0f, 0f, 0f);
isActive = false;
player.GetComponent<PlayerStatus>().Reset();
GameManager.instance.TriggerEvent(Type.ResetLevel);
}
This is the "restart" function on the monster, just to give an example on this mess
yeah this should not be controlling a player reset and game manager..
No, think of something like Outlast, where if the monster catches the player, they play an animation of the player being killed - like the monster collides with the player and 💀
2 extra references not needed, it should be other way aroud, it just throws events that manager listens for to react accordingly
ahh I see, well I would try to abstract out that 'death sequence' into its own thing which is in charge of orchestrating it from the top-down
monster control a player script messy..controlling game maneger? messy
Most likely not that, but you are talking about level resetting, respawning players, etc. You should be tracking all of that in one place probably.
it really is, I wanted to work on some camera logic, and ended up having to clean this up lol
its "tightly coupled"
because if you ever take out the player or game manager, the enemy breaks (esp without null checks..)
player.GetComponent<PlayerStatus>().Reset();
GameManager.instance.TriggerEvent(Type.ResetLevel);```
I think this is the sort of thing tht playables/timeline were desinged to solve, but I haven't really played with them
let me post what the gamemanager looks like right now
You need to look into observer pattern, and just fire some events
oh wow, that one kind of messed up the formatting
the Events calls is what i've been starting to work with to clean this up and start to use the observer pattern
your enemy / player should just be the publishers only, manager is the listener
hooo wee, looks like i'll be staying up for this
It's hard to know what all is listening to those events firing from your game manager, but seems like it is mainly your only Monster and Player classes. Just call the methods from the manager instead of firing events back and forth.
gotcha, do you think I should keep the Events as its own file, or insert what I have in Events into the game manager?
public class Events : MonoBehaviour
{
public static Action OnPlayerDeath;
public static Action OnPlayerRespawn;
public static void PlayerDied() => OnPlayerDeath?.Invoke();
public static void PlayerRespawned() => OnPlayerRespawn?.Invoke();
}
or more so i'm asking, which of these is 'best practice' - or does it even matter?
eh thats just an extra abstraction not needed imo
Well, it totally depends on how you structure everything, really. What I am saying is you don't need any of that Events stuff in that little snippet.
You already have your player and monster assigned in the inspector, so call the methods on the player and monster.
perfectly fine to keep it in the player itself
enemy just needs a Public method kill or whatever on player then invoke death event to restart, call anim or whatever from manager
alrighty, thanks guys!
now to sift through this nightmare and make sense of it, there's oh so many issues
Some other easy things to get some other improvements I can see:
- Change your GameObject assignments for monster and player to be their classes. Then you won't need to call GetComponent<> on the class you want. It will already be assigned. This also helps ensure you assign the correct thing.
- If you make something like that Events class later for some reason, it has no reason to be a MonoBehaviour, so just keep it as an independent class.
So something like
[SerializeField] PlayerStatus player;
[SerializeField] Monster monster;
?
Another thing to mention is that the player has a few more classes:
- PlayerCamera, for camera and body rotation with the mouse
- PlayerInteraction, for the interaction functionality
- PlayerMovement, for movement
- PlayerStatus, for when the player dies
not sure if that matters for that assignment?
btw when using static events make sure you ubsubscribe / cleanup when object is destroyed
normally good to do but especially with static events
Just for whichever class you need to be calling from the manager.
OnDisable for this?
I know we don't have anything that explicitly destroys any object in the game
ya or OnDestroy
always easiest to do this when possible. yes.
if there are thing that spawn at runtime or something , then you can use a static event there to invoke itself to the game manager
one more thing, so here you meant that the manager subscribes to events in player and monster?
yea like a 1 way street
the enemy / player shouldnt care about manager
i see i see
they just say "hey I did this" , and game manager reacts " okay im going to do this "
thanks! gonna go try this out
Can I have like an event to notify if a value changes on the same frame? Cause I have absolutely no idea when something is turning null, but doing logs on update is not very useful in this case...
You can have whatever you have the skill to make.
Yeah, then I don't have much lol
If you need help with something then you should consider providing actual information about the issue
This code works wonders when used just within itself, but I have a UI element that can set the draggedWaypoint from outisde it, and it works, until the last part, apparently something is making the dragged waypoint null before reaching the GetMouseButtonUp(0) part, thus not triggering any of that
Basically, if you click on the UI, it just spawns the point on top of the cursor and starts moving it, no matter where it is. The move part works, but the dropping does not
I have a button that I’m setting even system current on and in the debug it’s the correct button but the sprite swap is no highlighting it works fine on all my other buttons but I don’t no why on just this one button
!code 👇
but check all locations that access that variable and make sure that the references those use are not null
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
A tool for sharing your source code with the world!
I don't see anything that would set it to null in there mmmm.....
what about anywhere else that would be accessing that variable?
Oh, I was calling to drop it from an outsider OnPointerUp for some reason
I guess it's calling that first
anyone know what channel i would go to for problems with a video player?
im preety sure itd be here but i can still ask there sure
so quick clarifying question about the observer pattern,
if i'm going for an implementation that makes the GameManager into a subscriber, and the Player into a subject, do I understand correctly that it would go something like this:
// Player
public event Action PlayerDied;
public void Die()
{
// blah blah blah
PlayerDied?.Invoke();
}
// Gamemanager
[SerializeField] Player player;
Start()
{
player.PlayerDied += HandlePlayerDeath;
}
HandlePlayerDeath()
{
// do something here
}
and do I understand correctly, that once Player calls the Invoke, it sends a message to GameManager to execute HandlePlayerDeath()?
why are you negating Time.deltaTime?
its a count down timer
Yeah but why are you setting currentTime to negative deltaTime? What's the point in setting it to a negative, then checking if it's negative?
It's just always going to be that
basically you are just telling currentTime to be Time.deltaTime, but negative
so it should be time.deltaTime - 1
Should it?
deltaTime is the amount of time, in seconds, that the last frame took to render
i meant to put "?" sorry
So, if your game is running at a stable 60 FPS, you can just pretend Time.deltaTime is the same as writing 0.0166f
Setting it to 1 - Time.deltaTime would be basically setting it to 0.9834. What does that accomplish?
If you want a timer to tick down every frame, and you have a value that holds the time that frame took, what do you think you should do with those numbers?
wait so it should be curentTime = curentTime -1?
but i make it do that for every second elapsed
Think about it
Update runs once per frame
currentTime = currentTime - 1 in update means that it is counting frames
not seconds
If you want it to tick down every second, and you have a function that runs once per frame, you'd need a value that represents the amount of time in seconds each frame takes to load
i wana try figure it out without looking at the docs but i will if i have to
Now, where might you find that
yea i was gona say a seperate function but idk how to make it do it every second
So, what's Time.deltaTime? I've told you it a few times already
he said that too
the last frame
Right. In Seconds.
So, if you have a function that runs every frame
and you have a value that is how long that frame took in seconds
And you want to measure the passage of time in seconds
What might you do
maths but im half asleep so im stumped
brother, look at the docs
it's very very simple, you'll be surprised how simple it is
no additional lines or anything
your implementation is almost there, just one little thing to change
Let's think of it this way.
You are in a car that is moving at 60 miles per hour.
Every hour, you want to write down how far you've travelled. You can look at the number you wrote down last time.
When it comes time to write down the number, what math do you do to figure out how far you've gone?
oh
You have your speed and you have your distance travelled
yea im stupid ive just looked at the docs
say the delta time was 0.1s and i wanted to increse smth by 1 per s i would just do 1 * time.deltaTime
idk tho i am half asleep just tryna get this done before i go to bed
Right. And if you want to decrease something by 1 per second, what might you do then?
i meant + (1*time.deltaTime)
It'd be n += x * Time.deltaTime where x is however much you want to happen per second