#💻┃code-beginner
1 messages · Page 143 of 1
👍 much better
context with question ^
did you debug the values of the player pref variable to see if it is what u believe it should be?
yup
which variable is it? that should be loading into the game?
or which playerpref value are u working with?
this code at void collectstone
im mby stupid but how do i prevent dealing damage while in the trygger i want to deal the damage only once and i have to reenter the trigger
youre using the correct one..
OnEnter happens only once during the first interaction with the trigger
OnStay would happen every physics frame that you are in the trigger
If either object has multiple colliders this would run once for each collider.
well it will deal damage even tho it is in the tigger
then it might be exiting and entering over and over
u can test it with simple primitive shapes.. u can drag a box into the trigger, it'll only happen once..
its probably ur setup and colliders, like praet mentioned
no i have only one i just tested it on a wall and its will be doing the same thing
the second i touch the trigger the hp go down extremly fast
are u sure there isnt other scripts?
or the script isnt being disabled and re-enabled over and over?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
nope
so its becous of the method
ye
and a lot of projects
i dont much tho mostly use Tutorials
has to be.. if that debug doesnt go constantly.. then its not the trigger that happens over and over
very weird.. is ur TakeDamage() function called anywhere else?
in an Update loop of something
no
idk that doesn't make sense tbh, why would the function be running more than once..
but not the trigger that calls that function?
Add Debug.Log and see where it's being called
the stack trace will show it
in here
nice i fixed it
it was me being stopid
i forgot that i had dmg on the weapon set to 999 cus i was stesting somethign else
and i was just oneshoting the objects but beacous of the Invoke it was destroy them later thats why i thout they were geting kiled while inside the trigger
This is script where i save
This script to display
Idont know why the stone dont display while debug " stone display"
any one?
debug ur outputs and make sure they're getting modified with the values u expect..
then.. make sure ur animations arent controlling its position (overwriting ur code)
if its set to "Root Motion" the animation will overwrite the translation u use in code
thanks
just to be extra sure.. the better way to do it.. is to have a parent root object.. thats the object you move in ur code.. the animation and stuff should be Graphics.. it should be seperate from the logic.. and a child
iso u animate the graphics in the child.. but u move the parent container thats containing that child..
the animated graphics will just follow along.. b/c of being parented
awesome. understand
hello hello! So i'm in the process of creating a fangame, but i'm having an issue with the main menu. I'm trying to recreate Danganronpa's way of using a "Press Any Key" function to get the actual main menu options, but i can't figure it out?
Hey friends, i'm trying apply a force to a projectile based on a vector2 that is made up of the right analog stick axis' on a controller and my issue is that if the analog stick isnt moved to an edge, the projectiles generated are slower. I'd like to make sure all the projectiles are moving at the same speed. I get that the vector2 figures will be anywhere between -1 to +1 and having a vector2 thats like 0.2,0.01 will make the projectiles slower than something like 0.75,0.75 but im not sure what my options are here. The only other alternative i've thought of is to generate the projectiles moving Vector2.right but possibly rotate them?
Sir do you have any solution regarding my problem ? Or can you suggest another script .. my game basically need to collect calorie ..after collect calorie user can collect stone to go next level .. i want to save only stone and display in another scene .
normalize the vector
PlayerPrefs.SetInt("StonesCollected_Level" + SceneManager.GetActiveScene().buildIndex, stonesCollected);
PlayerPrefs.Save();
i dont use playerprefs
but i think its something about the way u try to save the build index with the string..
ahah, yes, but how do I make it so it gets rid of the "Press Any Key" text and shows the "Start" option and other main menu buttons.
Can you suggest another way to savs it? And appear in another scene ?
have you seen any of those PlayerPrefs assets in the Unity Asset Store
some of em has a window that u can look at that will show ur player prefs
it can help you debug
Start your journey by researching into using Unity's UI and Canvas components
excellent, thank you!
I use JSON and Serialized Data.. but thats pretty advanced for saving a random integer
like this one
Orite tq i will try
can help u visualize the playerprefs that ur modifying
instead of just trying to guess and having to debug the values all the time
it may help ya find a solution
if not just keep asking..
Anyone got any tips to deal with this stuterring?
It all seems to work pretty well physics wise, just not visually.
This is how I'm moving the player and the platform:
if(xMovement != 0)
{
float t = Mathf.SmoothStep(0f, 1f, Mathf.PingPong(Time.time * speed, 1f));
Vector2 newPosition = Vector2.Lerp(startPos, endPos, t);
// Calculate the delta position
Vector2 deltaPosition = newPosition - (Vector2)transform.position;
// Move the platform
transform.position = newPosition;
if (playerOnPlatform)
{
// Move the player along with the platform without interfering with velocities
playerScript.rb.position += deltaPosition;
}
}
Guys, how can I use input.GetAxisRaw for player control in unity
That's a very vague question. GetAxisRaw tells you the current state of some input axis.
You use it however you want to control your player object
The details of that are bespoke to how your player and your game works
can i use it for fps player movements?
tnx
im using unity 2017.4 on windows 7
That's a very old version of Unity and Windows
But, ok.
how can i add a dahsing fearue if my movement works like this, would this work
if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.D)) {
transform.Translate (Input.GetAxis ("Horizontal") * Time.deltaTime * speed, 0, 0);
}
if (Input.GetKey (KeyCode.UpArrow) || Input.GetKey (KeyCode.DownArrow) || Input.GetKey (KeyCode.S) || Input.GetKey (KeyCode.W)) {
transform.Translate (0, Input.GetAxis ("Vertical") * Time.deltaTime * speed, 0);
}
disable this code during the dash
and no, the link would not work
you cannot mix Rigidbody motion with transform.Translate
it seems I have a problem with a stack overflow
with the recursion, where for some reason, it gets repeated
and Now i can't even run the game without getting a stack overflow, even after restarting the engine
why wouldn't this get repeated?
You probably should start the new raycast from slightly further along in the original ray's direction
you can try to use some interpolation if its a rigidbody.. another solution would to be to parent the object to the platform while ur standing still.. unparent it when u start moving.. would also need to disable things like ur rigidbody and what not when u do and renable it when u get off of it
theres different solutions.
actually it could be just ur camera.. can use cinemachine to follow ur target smoothly..
also has more options
it should only repeat once after the reload timer is set to zero in the other part of the code
how much? like, 0.1 of a unit?
sounds like a decent start. Big enough to not hit the same collider in the same spot again, small enough to not screw anything else up
yeah ill do this
I'm interested on rigidbody interpolation, since i'm not sure what you mean by that. I've previously tried the parenting methods, and this is actually moving on from that, because it didnt work well with the physics, and I also used to use cinemachine, before I moved on and made custom camera movement
well i dont think its the rigidbody.. its not the rigidbody thats jittering
its the camera.. now that might happen if its parented to the player..
It's not parented for one
Ah, I've already got that turned on unfortunately
it basically takes where it is.. where its going.. and finds a middle ground
cinemachine is built into unity.. just need to go into the package manager get it..
im sure with its features u can get a smooth follow
since armor, maxHealth and health are all public bools in Unit
it has a great section of options for 2d scrollers just like this..
with deadzones and whatnot.. to keep the chracter int he center
I'll try making the camera idle and see if the issue persists to see it's my camera movement that's the problem, because I actually stoped using cinemachine because i wanted to accurately recreate the camera from the sonic classics in 90s
Run some debug code right before the if statement that checks if any of the variables in line 122 are null
Let's set up a 2D Camera to follow the player without writing any lines of code!
● Project Files: https://github.com/Chaker-Gamra/2D-Platformer-Game
● Playlist Link: https://bit.ly/3dg1X88
● Game Assets: https://bit.ly/3xVVLtJ
♥ Don't Click This! : https://bit.ly/2Zi3vu9
♥ My Second Channel: https://bit.ly/3jvI8g6
-----------------------------...
check out this video..
u can see things like damping
which would totally help ya out
Yea I made the camera idle issue still persists
hmm may have to code in a solution then
Yea I guess so
moving platforms are always a PITA
yea haha, thanks for giving a response though, appreciate it
thanks
Is your ide set up correctly?
The place where you write the code
its ur code editor.. VStudio VSCde
Well yeah, but will it auto finish your code and highlight errors and stuff?
Then your ide isn’t set up right
rb.AddForce(speedright * Time.deltaTime, 0, 0,);
one , too many
!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
• Other/None
heres a visual guide if thats ur taste
for visual studio ofc, if ur using visual studio code, you'll have to use a different source
could just copy/duplicate a script?
likely the type doesn't match the component or you're putting a scene object onto a prefab not in scene
TextMeshPro is the 3D text version. It's unlikely you're using that
use TMP_Text for the variable type
you probably want TextMeshProUGUI. But it's usually best to just use TMP_Text since that covers both of them
put the correct type TMP_Text
Hi, anyone know why this text(TMP) isnt showing up in the actual game?
not a code question. but it's also not on your canvas
The bright white lines are the bottom left corner of your canvas. Your text is outside (to the left) of the canvas.
oh thanks, i couldnt see it because it was so big
check the docs pinned in #📲┃ui-ux to learn how the canvas works and how to set up your UI
when I rotate my capsule in the scene the arrows for the z y and x pos doesnt turn with the rotation
why is that?
your tool handle is set to global rotation instead of local
and not a code question
oh sry but thank you
how would i offset a prefabs position by a vector3 taking account for the rotation?
use transform.TransformDirection and pass in your desired offset direction. but make sure to call that on the object whose rotation you want to account for. then you can just add that new direction to the position
do you mean offset it such as the rotation would be considered 0 rotation when considering position?
if the z rotation is 0, Vector3(0, 1, 0) would move it up, and if rotation was 180, same vector would move it down
if the object is not rotated then 1,0,0 would move it right, not up
taking into account the rotation of what?
just dont modify the rotation...
add the vector3 to the position as the offset.. the rotation will remain the same
crap your right
rotation is global.. localRotation is local
z+ is forward
x+ is right
y+ is up
still though, the answer i provided would solve your issue
#💻┃code-beginner message
alr, thanks!
you have 2 scripts with the same name
Not on a line
a different file
You have two scripts defining the same class.
yeah i just clocked i delted that buy now when i play my game my animations messed up (there is 2 animations playing while walking idk y)
im following tutorial rn its from 2 years ago
might be outdated that y idk
alr ig i gotta go through 40 mins of tutorial cuz its in episodes💀 🔥 ima j go sleep this makin my brain rot rn
if i want to add arms to my fps character, how should i start, should i add for each wepaon a pair of arms with different animations ?
Is there a code question in there
well yeah kinda
should i code in different animations for the arms and each and every gun
or should i do this
group them by animation type, try to keep it generic?
You could do animation rigging if you simply just need the hands in different places based on weapon.
what about the reload animation ?
skip the arms just use weapons as the arms
Either way, there is not (or barely) a code question here and you should not be asking in this channel
no code in the question, but i try to know how to aproach it for me to be easyer to code in the arms
Just do what's the least amount of work for your game or authoring pipeline
but i need the arms
it's esential
Is there a way i can use one script to change a variable from another script from a different object
get a reference to the instance of the component you would like to change a variable on. and that variable must be public or have some public way of changing it (like a public property or method)
Guys can you help me!
I use Unity Netcode, the players can move and now I want to move the camera to the center of the players, does anyone have any idea how to do this
I would appreciate any attempt to help 😔
obligatory: use cinemachine
Thank you a lot I will check this out
Can someone help. Its driving me crazy.
public void ShowGameOverScreen(bool show)
{
SceneManager.LoadScene("2");
}
Im pretty sure this is supposed to work. Considered from scene 0 to 1 it works. But from 1-2 no, 2-1 or 2-0 also no
Why??
You don't have any scenes named "0", "1", or "2"
im loading by index arent i?
wdy I am passing a number
No you aren't
wait
"2" is a string
yes, unless its a DDOL or static vars
YAY I am almost done with this
i have a reference to both the instance and the script of the instance, how can i change the variables in the object?
I am unclear how you'd have a reference to the "script" of the instance
do you mean you have a reference to both a GameObject and to a monobehaviour class you've created?
i have a reference to what says Image(Dialogue)
Image is the object
and dialogue is the script, the reference is to the script on that instance of image
while I am here can I link these together?
If I anchor them to top right wont they overlap each other.
Show me a screenshot of your inspector.
That is a reference to the instance of Dialogue that is on the GameObject named Image
referenceName.variableName
ah, I was getting tripped up by the "Image" name
Whenever i try that
nothing will happen, and at the bottom ill get an index error
wdym "index error"?
Show your code and your error
IndexOutOfRangeException: Index was outside bounds of the array
Then that would mean you're trying to get the index of a collection that is either negative or bigger than the count of the collection
Can you show the error
the variable name script is working completely fine btw, thats attached to the same object
Nothing here is indexing anything
i copied the error
Show the error
So then why didn't you paste it
That’s literally the error word for word
Include the stack trace
Its not an error in the code
its a red warning error i get after the codes ran
Yes, it is.
This is not a compile error your IDE could give you
It shows in unity
It's an exception, it has a stack trace
if you get that error, it's in your console
Is it possible to make a bool be false while a specific animation in an animation controller is playing?
Visual studio tells me i have 0 errors
Because it's not a compile error
it's in the Unity console because it's a runtime error in your code.
now show
the
error
some kinds of errors can be caught by the compiler before your code runs
these are compile-time errors. you'll see them in both your code editor and in unity, and they'll stop your game from running
like if you make a typo or try to assign a value that doesn't fit into a variable
IndexOutOfRangeException: Index was outside the bounds of the array.
dialogue+<TypeLine>d__8.MoveNext () (at Assets/scripts/ui/dialogue.cs:46)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
dialogue:startdialogue() (at Assets/scripts/ui/dialogue.cs:42)
dialogue:Start() (at Assets/scripts/ui/dialogue.cs:18)
The difference between compiler errors and runtime errors is important.
A compiler error means something in your code COULD NOT possibly work.
A runtime error is something that could work but for whatever reason failed when it tried
other errors occur when the code runs
that has nothing to do with your question
that's an error with your code accessing an array element that doesn't exist.
these are run-time errors
dialogue.cs:46
Okay, so it's dialogue.cs line 46
Which has absolutely nothing to do with the code you've shown
Because it shouldn’t
The variable i change never even appears in that code, its literally is just meant to show if it runs
Because what shouldn't
No, your question is useless, solve the error
If you want anyone to help you, post the code that's relevant to the error that you want to solve
don't just post some random code that's got nothing to do with it
The error would almost definitely be that theres nothing for it to run
No, the error is that you're trying to access an index outside the bounds of the array on dialogue.cs line 46
theres nothing for it to run because i cant give it anything to run because i do not know how
That's the entirety of the problem
This is literally not relevant whatsoever
Show the line of code
Your error literally says exactly what and why the problem is
foreach (char i in lines[index].ToCharArray())
So index is either negative or greater than the size of lines
So how about show the actual !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
instead of us having to basically beat the information out of you like lunch money
i just stopped the error by adding 1 thing for it run, so it was because there was nothing in it
theres nothing in it because im trying to learn how to change variables from other objects
which is why i am here
I'm kind of confused by the whole conversation. It feels like you don't really want help?
Why not provide what was asked for so many times?
show
the
code
Certainly is an extremely frustrating conversation, where I'm considering just delivering a mute
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
people do not enjoy having to play a game of 20 Questions
learn how to use a coroutine
Use coroutines.
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Linq;
public class dialogue : MonoBehaviour
{
public TMP_Text textcomp;
public string[] lines;
public float textspd;
int index;
public bool troo = false;
// Start is called before the first frame update
void Start()
{
textcomp.text = string.Empty;
startdialogue();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if(textcomp.text == lines[index])
{
NextLine();
}
else
{
{
StopAllCoroutines();
textcomp.text = lines[index];
}
}
}
}
void startdialogue()
{
index = 0;
StartCoroutine(TypeLine());
}
IEnumerator TypeLine()
{
foreach (char i in lines[index].ToCharArray())
{
textcomp.text += i;
yield return new WaitForSeconds(textspd);
}
}
void NextLine()
{
if (index < lines.Length - 1)
{
index++;
textcomp.text = string.Empty;
StartCoroutine(TypeLine());
}
else
{
gameObject.SetActive(false);
}
}
}
Not reading resources, not sending requested information, being randomly argumentative
i argued where there was something they didn’t understand about the code
Because i didnt explain it fully
Then fucking post it
you asked about a problem with X and then gradually revealed that it was actually Y
!code please link to large codeblocks
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
a completely unrelated problem
i thought the error code was related, it was an accident
i only first noticed when i started this
So it looks like lines is set in the inspector and you gave it nothing
and then you didn't read the resource on stack traces I sent you twice, and started an argument about errors for no reason
to bring us back to the original point: do you now understand how to modify a variable on another component?
No, because it does still not work
as the original problem says
the line of code
dia.troo = true:
is not doing anything
ill post the code again
How do you know
Only do so in a paste site please
#💻┃code-beginner message
troo is public
so i can monitor if it changes
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class camtext : MonoBehaviour
{
public cammove script;
public GameObject obj;
public dialogue dia;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (script.count == script.time)
{
obj.SetActive(true);
dia.troo = true;
}
}
}```
Then you are either looking at a different instance or something else is changing it back
Have you checked whether that code is running
then dia.troo is being set to true, end of story
Can you check a bit harder, without any assumptions, by using the debugger or placing a log
as long as something else is not activating whatever that object is
so yes, let's check this assumption
okay
Log dia.troo after you set it. See what it prints
after removing that line of code
the object does not activate
meaning that code 100% runs
Log dia.troo after you set it. See what it prints
i did this
i checked
I got told to log it afterwards, wait a second
You just want me to use a regular debug log right?
Preferably you would use the debugger, but I doubt you're going to
i don’t know what that is
No I want you to use the premium DLC version that comes with a hat
https://www.youtube.com/playlist?list=PLReL099Y5nRdW8KEd59B5KkGeqWFao34n no time like any time to learn the debugger
What does it say
yeshhh
UnityEngine.Debug:Log (object)
camtext:Update () (at Assets/scripts/camera/camtext.cs:25)
How is a boolean set to "yeshhh"
I did that
Debug.Log($"{diag.troo} - {diag}", diag);
Log dia.troo after you set it. See what it prints
Don't just log a random word
Log something useful
Like I said twice
This will print the value, the object (its name), and will allow you to select the log and it will ping the object in the scene/project
thank you
this will show you what you're actually referencing, which may not be what you expect
True - Image (dialogue)
UnityEngine.Debug:Log (object,UnityEngine.Object)
camtext:Update () (at Assets/scripts/camera/camtext.cs:25)
So, the dialogue component on the object named Image has troo set to True
So it's set to true, and you can click on the log, look at the object it pings, and it should also be true
how the fuck
It's a different instance isn't it
Theres only 1
I understand that literally everything says its true except for the game which isn’t
Show a screenshot of the object after the log prints
Can you show your setup
the inspector of it?
Idk if thats my setup
idk what u mean by setup
And is this object highlighted when you click the log
it doesn’t seem to
Can you record a video of this happening
tbh at this point i give up
im just gonna do it differently this is dumb
thanks for the help tho
Either something else is setting it back to false, or you are. That's the only options here
If that's not the object that highlights then it's a different instance
And the specific variable we're asking about being highlighted in blue really doesn't give me confidence that it's the code's problem
Yes, it looks like it was just changed. I think we're being bamboozled
Yeah, I don't know how you get that white border around a boolean, but if the label was selected the field wouldn't have an outline
It was always correct XD
Ah, it's the hover state
Selected the label then hovered? No idea, either way, video evidence of this happening would be required to go any further
hey! does anyone know a way i can move an object from the scene inside a list, remove that object from the scene and still keep it in the list for later use
prefab
no work :(
either that or im using it wrong
i have a prefab saved in a variable which i reference to and add to the list before i delete the object. but the prefab gets deleted with it
Show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
The instance needs to exist in the scene if you're wanting something other than a reference to the prefab. Maybe consider scriptable objects if you're needing scripts with access from the inspector without needing a game object in the scene. Note: SO are normally expected to be immutable
Guys, i did the ide thing for VSC and i literally followed every step and the ide yet isn't configurated, what happens?
if(Input.GetMouseButton(1))
{
var objectCheck = Physics2D.OverlapBox(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.one * 0.125f, 0, LayerMask.GetMask("Furniture"));
if(objectCheck)
{
gameManager.furnitureInventoryList.Add(objectCheck.gameObject.GetComponent<furnitureStats>().furniturePrefab);
var listReference = gameManager.furniturePlacedList.Find(obj=>obj.name==objectCheck.gameObject.transform.GetComponent<SpriteRenderer>().name);
gameManager.furniturePlacedList.Remove(listReference);
Destroy(objectCheck.gameObject);
}
}
Did you get a net sdk error pop-up at the bottom right of VSCode?
yep
Install .NET https://dotnet.microsoft.com/download and restart your computer
its messy as hell since this is my first time working with lists but what i want to do is when i right click, i "stash" a placed object by moving it from a list of placed objects to a list which serves as inventory that i can place again later
This code is a mess, I have no idea what's going on with most of this list logic
doing things by name is a bad look, really should figure out how to make that same query by reference. Also, if you're just Finding to then remove, just call Remove with that same query?
this function is called in update(). however, my crosshair image never disables itself !
i called debug.log() inside the condition where it disables my crosshair and it works
what type is crosshair
Does it hide itself if you manually disable it?
yes
Show the inspector of the crosshair
Log the value of current item
see, the problem is
there are child images inside the parent panel
thats why i want to disable it entirely
Then use a CanvasGroup to hide all the children
Also works of course, but depends on what you want and they have performance differences
there is no defined setactive method inside a Image object
SetActive on the gameobject
hey guys i am trying to make a inv systen but the drag and drop is not working i also have a hover bool to check if that is working and that isint working i have turned of raycast target on the drag/drop img does some1 know what is hapening(copied the code from the vid sorce bc i tought it was that but it aitnt)
here is my revised code
oh right yeah if you want to disable the children just disable the object
I read that wrong
You're still reading directly from a Quaternion btw
Idk what causes this, and i dont even know if it's a coding problem (if it's not, please lead me to the channel) when i shoot with my weapon it goes to the right, like this, the blue arrow represent to where the bullet goes
rotate the shooting point?
Let me try
Are you certain it's not being set to true again? Place the log outside of the if statements.
Ty, it was a very stupid problem, idk how i could not figure it by myself
Also #💻┃code-beginner message
rotation.z isn't an Euler value.
np sometime we all need some help
how do i rotate a UI element through scripting?
It isn't so much as rotating that's the problem but that you're using the z component of a quaternion, which isn't an Euler value.
#💻┃code-beginner message
should i change my assigned object to this?
how do i rotate the camera?
i did this and it worked!!!!
your other method would be fine too but you need to use those current euler values as well
what was i going to ask
uhhh h
RIGHT
ok
how do i make objects have two layers at once?
i want the ground to be both grappleable and walkable(whatIsGround layermask)
You can't
Tag it as something specific and then add that to anything that the masks that look for grappable or walkable surfaces
imagine if unity tags were bitwise enum
I'd probably use them
wouldn't even need to component search and instead just reference the gameobject tag when casting
hey guys i am trying to make a inv systen but the drag and drop is not working i also have a hover bool to check if that is working and that isint working i have turned of raycast target on the drag/drop img does some1 know what is hapening(copied the code from the vid sorce bc i tought it was that but it aitnt)
Any idea why this code throwing an error when I try to add to the dictionary?
public Dictionary<string, string> language = new();
language.Add("apple", "ringo");
You can't put code just floating in the class
it needs to go in a method
If you want to initialize the Dictionary inline you can do this:
public Dictionary<string, string> language = new() {
{"apple", "ringo"}
};```
otherwise - use Awake:
void Awake() {
language.Add("apple", "ringo");
}```
yes
is there a way to set the base layer of an avatar controller's speed to zero while an avatar mask layer moves at full speed?
Sounds like an #🏃┃animation question
I mean a way to control that speed in the code
Someone may know why when i try to make PistolMesh active (it's not a mesh, it's a GameObject) it dont works, but somehow if you enable the object again (because it does disable on start) it also shoots, which is strange
How do I return a "random word" from dictionary?
string GetRandomWord()
{
// Use Random.Range to get a random index within the list
int randomIndex = Random.Range(0, JapEngDict.Count);
// Get the word at the randomly chosen index
string randomWord = JapEngDict[randomIndex];
// Remove the selected word from the list
JapEngDict.RemoveAt(randomIndex);
// Populate text if this condition is met.
if (JapEngDict.Count == 0)
{
inputField.placeholder.GetComponent<Text>().text = "No more words in the list!";
Debug.Log(inputField.placeholder.GetComponent<Text>().text);
textElement.text = textValue;
return null;
}
// Return the selected word
return randomWord;
}
Wait, maybe because it's unabled it can enable himself again?
I think so, am sorry for annoying
select a random key from a list or array of all the keys
Well... sounds pretty self explanatory - but show your quality and graphics settings windows
Do you know a good document for this? So I can see examples and what not
scroll down - you'll have mixed assets
that one is a URP asset
what are the others
and what is the Graphics Settings set to
I mean you have the code for randomly selecting from a list or array right in your example
My editor crashed without any errors
int randomIndex = Random.Range(0, JapEngDict.Count);
// Get the word at the randomly chosen index
string randomWord = JapEngDict[randomIndex];```
That thing just needs to be a list or an array, not a Dictionary
Is there any crash log to know what caused it?
How do I do the same thing with Dictionary? Sorry I'm super new to using Dictionaries
sorry not scroll down - but select all the different quality levels
you don't - you need a list or array basically
you could get an array of all the keys in the dict if you want
e.g.
string[] keys = JapEngDict.Keys.ToArray();```
Error CS0119 'ReadInput.JapSpaDict()' is a method, which is not valid in the given context
what's JapSpaDict
like the error is saying, that's a method
you're trying to use a method like it's a variable
private void JapSpaDict() { Dictionary<string, string> JapEngDict = new Dictionary<string, string>(); JapEngDict.Add("apple", "りんご"); }
this code does absolutely nothing
Sorry I changed the names
it creates a new dictionary, adds something to it, and then you lose reference to it forever
What's the proper way to add a reference to it?
you didn't just change names
assign it to a variable that exists outside the function
I'm trying to associate the Japanese word with the English
private Dictionary<string, string> JapEngDict = new Dictionary<string, string>();
private void JapSpaDict()
{
JapEngDict.Add("apple", "りんご");
}```
Thank you
you prob want that to be more flexible with params
i have no idea why you have this function though - that's a weird function
what's the point of it
Is something else going to call it?
I don't think it would help to see the game
Just an explanation of what the function is and what it's for and where it would be getting called and why it's called JapSpaDict
I'm trying to associate two different languages with one english word
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
anyway back to this you would use your dictionary, which is called JapEngDict.
make a struct as the value
ohh nvm you mean like a translate type thing?
oh okay so how do you plan on filling this dictionary
I can manually type it I don't mind
The end goal is 100 words doesn't need to be anything fancy
Is Dictionary really the best data structrure for this?
sounds like it, esp if you want 2 languages per word
Okay
You can make 1 word as key and then custom struct/class as values, 1 string per language?
Okay let me try
where does english come into play?
It is to key value pair the dictionary value
Why?
i.e. apple -> りんご
How is English involved in the game?
Well technically it's not but just for easier record keeping
Sounds like you just want a mapping from the spanish word to the Japanese word
and/or vice versa
Yes
But I'd like to map it to English for reference
string GetRandomWord()
{
string[] keys = JapSpaDict.Keys.ToArray();
// Use Random.Range to get a random index within the list
int randomIndex = Random.Range(0, JapSpaDict.Count);
// Get the word at the randomly chosen index
string randomWord = JapSpaDict[randomIndex];
// Remove the selected word from the list
JapSpaDict.RemoveAt(randomIndex);
// Populate text if this condition is met.
if (JapSpaDict.Count == 0)
{
inputField.placeholder.GetComponent<Text>().text = "No more words in the list!";
Debug.Log(inputField.placeholder.GetComponent<Text>().text);
textElement.text = textValue;
return null;
}
// Return the selected word
return randomWord;
}
How do I convert this from list previously to now the dictionary?
Probably would do something like:
[Serializable]
public class Word {
public string English;
public string Spanish;
public string Japanese;
}```
Then you'd have :
```cs
public Word[] allWords;
Dictionary<string, Word> mappings = new();
void Awake() {
foreach (Word word in allWords) {
mappings[word.English] = word;
mappings[word.Spanish] = word;
mappings[word.Japanese] = word;
}
}```
then you have a map from all the languages to each other @dense root
and you just fill the words in the inspector
and:
Word GetRandomWord() {
return allWords[Random.Range(0, allWords.Length)];
}```
nice 😛 i was doing exactly similiar
don't forget [Serializable] on the Word class
just write UnityEngine.Random.Range
it will go away
it's because you have using System; and using UnityEngine; and they both have a Random class
this happens when two namespaces share the same class name, in this case Random
another solution can be to write using Random = UnityEngine.Random
this tells the computer you want only Random from that namespace when using it
just noticed the other day vs was adding namespaces even if they were conflicting with my other namespaces
How do I return a string from my GetRandomWord method?
ive had that happen too idk where from
I think it doesn't remove the namespace from the undo history if you accidently add the wrong class call
access the specific word with .
Ohhh nice
depends which languag eyou want
How do I add words?
in the inspector
ohh
I asked in animation chat but it kinda applies here too, is there a way to do something like this? (Enemyloco is an animation controller and this specific function is read only)
I only want to change the speed of a single state or layer not the whole controller
Make a float parameter in the animator
Then in the state you can do this:
Oh sweet ok thanks
I'm getting a null reference error.. any ideas?
Surely you can figure this out
lol Let me keep trying at it, I've tried all the options in the inspector
What's the inspector got to do with it
Isn't it asking me to select the Text Element in the inspector?
To reference it to the code?
It's not asking you to do anything
what are you trying to access on the line of code that's throwing the NRE
I'm trying to access InputField
No
Which one?
Japanese
Where's that?
To the left
I mean in the hierarchy
Above Spanish
What's it called?
It's looking for InputField(Legacy)
Yep
oh

Okay and show the inspector of the object named InputField(Legacy)
how do i know what values to put for cycles offset 😇
I have never figured out how to get vscode to put opening brackets on the same line
inputField = GameObject.Find("Japanese").GetComponent<InputField>();
No, the object named InputField(Legacy)
The one you're looking for in code
So, follow up question:
Why are you using Find at all
Just make a public InputField variable and drag it in
I could try that
How do I convert this to use a word as defined before?
japInputField.placeholder.GetComponent<Text>().text = newPlaceholderText;
This is how the inspector looks now
If the problem's just more NREs, the solution is the same steps every time https://unity.huh.how/runtime-exceptions/nullreferenceexception
Also, inTheAir = !hit.collider.CompareTag("Ground");
I assigned my Inputfield in the inspector I'm not sure what's creating the NRE
the one in your screenshot has nothing to do with an input field
trying to call the "StopPlacement" method from the "PlacementSystem" script to use in the "CameraPosition" script, whats the correct way of doing this?
public PlacementSystem Whatever;
void Start() {
Whatever.StopPlacement();
}
what is whatever supposed to be?
it's a name, call it whatever the hell you want
ah ok
Does CameraPosition have a function named StopPlacement?
No it's PlacementSystem that has the function, but vertx's code worked
i am currently working on a 2d platformer gun aim system. it aims where the cursor is pointing, which works great, however im struggling to try to limit the rotation (limit the gun from going over 180 degrees so that it doesnt look weird when its pointing to another direction than my character)
I tried to do it with (as you can see in the bin) " difference.x = Mathf.Abs(difference.x);"
which works great if the player faces right, but doesnt work when the player faces left
how would i go about fixing this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Why is it even after adding a code to stop it from bouncing like this it just doesn't seem to work
i know this is a while after your message but tysm for the tip! looked into SO and they are exactly what i needed. really functional and helped me clean my code up a lot
i know this is probably a really inefficient way to do it, but i simply did an if else statement:
if (facingLeft)
difference.x = -Mathf.Abs(difference.x);
else
difference.x = Mathf.Abs(difference.x);
atlest it works, if anyone knows something better, pls let me know
the method right before (lower then) the top one(log) ?
how is it inefficient? It's a single if statement and probably the least of your worries if anything
Hello, anyone here that could help me with a very basic jump animation in 2D game? I've set up the animations for walking and idle properly and succesfull. But for some reason my Jump animation gets looped when mid air, despite the fact I unchecked "Loop Time"
neat thanks, lemme test when i got back 
what is the transition condition and how are you setting it
I set it from any state to jump when grounded is false and from jump to idle when grounded is true
chances are its going from Any State to jump constantly, unless you did uncheck Transition to Self
😭
I need help with this, it tells me here that the text does not exist in the current text, how can I fix it? is to turn shadows on and off using a toggle
so where did you make those two ?
here
another win for chatgpt, giving you code that doesnt even compile
if you really cannot solve the issue of "does not exist in current context", drop what you are doing and go do some basics of c#.
How about asking ChatGPT to write code that exists
My absolute favorite from chatgpt was the Color.Distance incident someone had
for me it is not necessary
it clearly is necessary for you. you are blindly copy pasting code, and not even aware of what the code is yourself.
I know what it is
Funny enough I actually have that exact extension method because of a potion mixing VR minigame 🤣
then why are you trying to use a variable that does not exist
🤨 maybe chatgpt learned it from some public repos lol
Not mine haha
I called it distance rather than difference simply to be the same as a Vector3
Now Im sitting here thinking what the cross product of two colors look like
Hey, you've probably forgotten about the whole issue I was having, but I thought you could find this interesting or helpful. I managed to fix the problem.
Previously I was just updating the player's rigidbody positions, which was great physics wise, but caused terrible stuttering visually.
I tried moving just the transform, and there was no stuttering, but the physics became all janky. So i tried moving the rigidbody positions first, then the transform along with it, and it fixed the stuttering somehow. Also needed to round the player's offset on the platform to the nearest 1/32 for a pixel perfect camera, otherwise stuttering would continue:
float roundedOffsetX = Mathf.Round(offsetX / 0.03125f) * 0.03125f;
playerScript.rb.position = transform.position + new Vector3(roundedOffsetX, 1);
playerScript.transform.position = transform.position + new Vector3(roundedOffsetX, 1);
playerScript.sprite.position = transform.position + new Vector3(roundedOffsetX, 1.25f);
oh and also had to change interpolation mode to none
assuming non zero values (and alpha always 1), i think it would just be like applying an offset in that circle you can use to set colors in inspector. Like green * white = red, red * white = blue, blue * white = green. When reversing the order, basically just go in the reverse way around the circle. white * green = blue etc
If using like fractions (not fully green) then idk lol but its probably similar just more dim
Would be a interesting experiment haha
One can probably make a whole indie game where colors and directions are the same thing haha
I have a question.
Is it possible to create a custom editor script so that I can drag a prefab into a list of sprites (sprite[]) in the inspector, loading all the frames from that prefab?
i was experimenting with more decimals values in it, id say itd be pretty hard to design a game with it lol. Im not the best at visualizing cross products in 3d, but the offset thing I said is basically what happens if you use a pure white value for one color. When one color isnt pure white, it'll start to kinda fade between black and an offset color
Sorry if I asked this in the incorrect thread
to me, the question doesnt really make sense. You said you want to drag a prefab into a list of sprites then load all the frames
...or are you not experienced with that sort of thing?
im not entirely familiar with custom editors, but that the "drag a prefab into a list of sprites" part doesnt sound like something that'd be fun to handle. You could probably just make a field for the prefab, then a button which starts the logic instead
also yea I dont know much about that file type sorry
@crystal sierra You can ask in #↕️┃editor-extensions but like bawsi said, EditorGUILayout.ObjectField for the prefab and a button would be easiest
Thanks. I'll try that
Guys I have a serious problem..... In my car game... The speed of my car is much and it's acceleration also but in rigidbody 's info section the speed showing is something in 0. Something... Why?? But in game speed is much... And in speedometer script I converterted m/s (SI Unit) to km/hr..
show relevant !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
is there a way to increase the resolution of the game?
other than
scaling everything up?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Speedometer : MonoBehaviour
{
public Rigidbody target;
public float maxSpeed = 0.0f; // The maximum speed of the target ** IN M/S **
public float minSpeedArrowAngle;
public float maxSpeedArrowAngle;
[Header("UI")]
public Text speedLabel; // The label that displays the speed;
public RectTransform arrow; // The arrow in the speedometer
private float speed = 0.0f;
private void Update()
{
// The speed is now the magnitude of the velocity in meters per second.
speed = target.velocity.magnitude;
if (speedLabel != null)
speedLabel.text = ((int)speed) + " m/s";
if (arrow != null)
arrow.localEulerAngles =
new Vector3(0, 0, Mathf.Lerp(minSpeedArrowAngle, maxSpeedArrowAngle, speed / maxSpeed));
}
}
@slender nymph the code
now show how you move it
By wasd keys
jesus christ, i obviously meant the code
Oh
you seem to have already forgotten how to correctly share !code
but the issue is that you are moving via the transform. that does not change the rigidbody's velocity
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine;
public class SimpleCarController : MonoBehaviour
{
public float initialAcceleration = 10f;
public float accelerationIncreaseRate = 5f;
public float steeringSpeed = 5f;
public float brakePower = 20f;
public float inertiaFactor = 0.95f;
private float currentAcceleration = 0f;
private float currentSteering = 0f;
void Update()
{
// Acceleration
if (Input.GetKey(KeyCode.W))
{
currentAcceleration += Time.deltaTime * accelerationIncreaseRate;
}
else
{
currentAcceleration *= inertiaFactor;
}
// Steering
currentSteering = Input.GetAxis("Horizontal") * steeringSpeed;
// Braking
if (Input.GetKey(KeyCode.S))
{
currentAcceleration -= Time.deltaTime * brakePower;
}
// Move the car
transform.Translate(Vector3.forward * currentAcceleration * Time.deltaTime);
transform.Rotate(Vector3.up * currentSteering * Time.deltaTime);
}
}
Oh ..... But how to fix that
move using the rigidbody instead of the transform
or pass the speed and direction from this component to the speedometer component. but if you want to move it via the transform why does it even have a rigidbody
Ill do it
Is it true that there was an era where unity devs dont have UI objects and must do UI stuff via purely GUI?
Yup
what is the best way in a 3d world to find a path? is it navmesh or do i have something else?
navmesh is unity's built in way. otherwise you could get some asset or implement your preferred pathfinding algorithm manually
!support
Take a look at #🔎┃find-a-channel
:warning: This is not a channel for official support.
Please do not ping admins, moderators, or staff with Unity issues.
Almost all channels are help channels, consult https://discord.com/channels/489222168727519232/531961806646935564 where to ask and #854851968446365696 on how to ask.
ok thanks
As we know, the List<T>'s array size increases by doubling the starting point of capacity 4,8,16,32,64... based on the count. How does it work if i pass Initial Capacity? Lets say i said "100" at the capacity at initialization of new list. Will it double to 200 or snap to the 128?
Collision doesn't work often. When I'm shooting from starting position it works fine but if I move torward to wall or rotate tank about 90 degrees it doesn't work
if anyone is free i have a slight problem with my code, (context: im learning how to do 3d movement in unity and i am having issues with line 34 heres the code)
(and heres the error Assets\Scripts\Playermovement.cs(34,70): error CS0131: The left-hand side of an assignment must be a variable, property or indexer )
Fixed it dont worry
!ide @brisk escarp
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
• Other/None
Helps you detect them later on
thanks, had that on my old laptop and forgot to add it to my new pc.
please can someone help me with this?
change your rigidbody collision detection from Discrete to Continuous or Continuous Dynamic, please consult the docs to see which one fits your situation the best
What
I need help, the next code it's supposted to save another boxhelp height on boxHelpHeight var, that works correctly, cause the log shows me the values changing... But when i try to apply the var's value to the right boxhelp it doesn't work... What could happen? The right boxhelp changes it's vertical size to a really small one and it doesn't do nothing with that code```csharp
boxHelpHeight = GUILayoutUtility.GetLastRect().height;
Debug.Log("BoxHelp Height: " + boxHelpHeight);
// RIGHT BOXHELP
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(boxHelpHeight), GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.25f));
GUILayout.Space(2);
GUI.backgroundColor = new Color(46f / 255f, 204f / 255f, 113f / 255f);
propertyAdditionMenu.Draw();
GUILayout.Space(15);
GUI.backgroundColor = Color.white;
EditorGUILayout.EndVertical();```
@slate gale there
Is your wall a plane or cube
Should probably consider asking your editor scripting question in #↕️┃editor-extensions
Yes i’ve seen the video and the code, i already made a suggestion
Do you use a plane or box mesh for your wall?
Yesterday i published the question there, but nobody has answered it...
I presume they're using HDRP and that's a planar reflection probe
Maybe no one knows. Ask chat gpt maybe it can find a bug
Check the assetstore
nohing good there
Too bad
its for school project im not wiling to pay
i made it but it horible
School
and broken
Believe me, i've tried it with all AI chat-bots that exists on the world hehe
Then idk sorry, not too experienced myself with editor scripting 🙁
@autumn arrow don't cross-post
oh, don't worry, i'll just keep looking for an answer myself
If you have a specific question, ask it, instead of asking something so general and requiring people invest in a conversation with possibly no ends
are you talking to me?
no
One has to wonder why you are writing Editor scripts using IMGUI and not UIToolkit which is a much better solution
honestly idk... when i started creating the window i didn't know about it existence... so i started with IMGUI and i didn't wondered about wich one is better... and know, if wanted to use UIToolkit i'd need to reestruct all code (wich is quite big)
honestly, you could have done it in the time you have been waiting for an answer to your question which is so niche that I doubt anyone else can help you with
one of the reasons I stopped using IMGUI was because expecting it to behave rationally is unrealistic especially in edge cases
i followd a tutorial double checked it twice
and my animation is still bugged
when i move the movement animation and jumping is at same time
So, you really recommend me to restructure all my code to implement better unity ui toolkit?
It will be the only option in the future, so yes. IMGUI has been secondary for the Editor for ages
yes, it does have a bit of a learning curve but if you have ever done any webdev then you are 90% of the way there
really? On the basis of your question and the code you incorrectly posted an answer is impossible
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
better post it like text
Is it more visual working with that unity UI toolkit...? I just wanted to create an small window for a little asset
it can be both, it is certainly visual debugging which is very nice
It looks like you're trying to run the debugger.
do you see this up top? if so, hit the red button to stop
can anyone offer tutoring in beginning development in Unity or UE?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
In this part, we will take care that our player can only jump while he is standing on the ground.
Github repository:
https://github.com/codinginflow/2DPlatformerBeginner
🎓 Learn how to build a 2D game in Unity (beginner): https://www.youtube.com/playlist?list=PLrnPJCHvNZuCVTz6lvhR81nnaf1a-b67U
🎓 Learn how to build a 3D gam...
folllow dis tutorial from episode 1
it really helped me understand basics
Is that the current version of Unity? my problem was i was following an outdated tutorial for a while but everything was updated and moved around,.. it was a nightmare
i mean im up to episde 7 and only one problem where i found a fix in the comments and there are 13 episodes im pretty asure
i learned basic scripting stuff , how to import models,how to create 2d maps,and more unity stuff
Okay you made it farther than I did with the Domestika tutorial im referring to
I trust you Batman
i can show you my progress i have got up to
if you want
or you can watch the video i sent
thats where im at towards the end
I need help!!!
How can i install c sharp on windows 7?
or enable c sharp snippet on vs code
!vscode
you also need to prob download .NET sdk
i have three 2d rigidbodies(fuel tank, engine base/mount and the engine bell) each is connected with a fixed joint to the one above it. pressing a/d should rotate the engine while the base does not move. what really happens is the engine base rotates, while the bell stays in the same rotation(relative to the base). any ideas why this happens?
i'll copy the code i use
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controls : MonoBehaviour
{
public float throttle, thrust, rot, gimbal;
public Rigidbody2D rb, mrb, trb;
public GameObject mount, tank;
void Start()
{
throttle = 0f;
thrust = 170f;
mount = GameObject.Find("Engine Base");
tank = GameObject.Find("Fuel Tank");
mrb = mount.GetComponent<Rigidbody2D>();
trb = tank.GetComponent<Rigidbody2D>();
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.LeftShift))
throttle += Time.fixedDeltaTime;
if (Input.GetKey(KeyCode.LeftControl))
throttle -= Time.fixedDeltaTime;
if (Input.GetKey("z"))
throttle = 1f;
if (Input.GetKey("x"))
throttle = 0f;
mrb.rotation = trb.rotation;
rot = mrb.rotation;
if (Input.GetKey("a"))
gimbal = -15f;
else if (Input.GetKey("d"))
gimbal = 15f;
else
gimbal = 0f;
rb.rotation = Mathf.Lerp(rot, rot + gimbal, Time.fixedDeltaTime*10);
throttle = Mathf.Clamp(throttle, 0f, 1f);
rb.AddForce(thrust * throttle * transform.up);
}
}
firstly, don't use Input in FixedUpdate
why?
because it will not work correctly
its been working correctly so far
notice how you've had to use GetKey?
I am currently working on a Unity project that involves multiplayer functionality using NGO (Netcode for GameObjects). I am facing challenges in synchronizing bullets between the server and clients.
Specifically, I am encountering issues with ensuring that when a player shoots a bullet, its position, and other relevant information are synchronized correctly across the network for all players.
If anyone has experience or insights into properly synchronizing bullets in a Unity multiplayer environment, especially using NGO, I would greatly appreciate your guidance or any code snippets that could help me troubleshoot and resolve this issue.
whats wrong with using getkey?
GetKey fires for each frame the key is held down
what should i use then?
GetKeyDown in Update would be favourite
i cant do getkeydown with throttle controls
anyway i dont think input has anything to do with the wrong object being rotated
well, you're setting rb.rotation
that's going to rotate whatever object that rigidbody is attached to
and its attached to the engine bell
how is the engine bell connected to the rest of the ship?
note that parenting rigidbodies to each other can cause unexpected behavior
ah, okay, good
engine bell -> engine mount -> fuel tank
Is the ship a lot more massive than the engine bell?
and how is the bell jointed to the ship?
fuel tank has a mass of 10, engine has 1
if the joint doesn't permit free rotation, and you change the rotation of the bell, the entire ship will have to rotate
I haven't done a lot with joints, so I'm not sure what the "correct" way to do this would be
i used a fixed joint but i dont think thats the problem as its only the engine base that gets rotated, not the entire rocket
A fixed joint forces two rigidbodies to maintain the same relative position and rotation
You either need a different kind of joint, or you need to update the rotation the joint is trying to maintain
there was some funny wobble going on between the fuel tank and the engine base so in the script i set the rotation of the base the same as the rotation of the fuel tank and then rotated the bell relative to the base
I use joints a little, but I'm not quite experienced enough to know what the best option is here
Maybe ask about this in #⚛️┃physics
i tried going for a hinge joint but i couldnt figure out how to set the angle in the code so the engine was just flapping around freely when turned on
relative joint fixed the issue
yay
are scriptable objects ddol?
i wanted to make scriptable objects as a way to save level data, but idk if that would work
SO's exist in project folder
they can kinda hold their data yes, but they will get reset per restart of the game (closing and reopening)
thats fine
i can implement a save system then
i was just thinking an SO would make sense because levels all hold the same data, such as like time and stuff
just try it for now, last time i tested, I used SO's to send data from 1 scene to another and that worked
I did use an Instantiated(so) btw, and they were referenced by a singleton ddol
not really sure if that was the reason the data persisted
No.
A ScriptableObject, like any other Object, will be unloaded some point after all references are lost
If Scene A references an object and Scene B doesn't, and all other references are lost, then the object unloads if you load Scene B in single mode
in this case, you have a reference, so the object stays alive
What is this singleton business i keep hearing about
yea quite had to clarify that cause i doubted their case will be the same as mine before
When the object is reloaded, it will have its original serialized values (again, as would be the case for every Object)
a singleton is something you have just one of
classically, you'll make an instance and stick it in a static field
I store some runtime data in scriptable objects for my settings system
in what class would u make that in?
I load an object that references all other settings objects, either directly or indirectly, when the game starts
so all of the objects stay alive forever
arent you familiar with singletons yet?
in this case, you better make a new class
sticking it to another calss will just make that class messy
Scriptable objects do not make sense for actually saving data
You should create a serializable class that holds all of the data you need
and then use something like Json.NET to serialize and deserialize that class
[System.Serializable]
public class LevelStats {
public float completionTime;
public float score;
}
for example
We can serialize SO's though, cant we?
I remember grabbing a tool before that can do so
Not without some extra legwork, at least
You're not supposed to directly construct ScriptableObject instances
and naïvely trying to serialize and deserialize them would mean you're constructing a new instance
i remember that tool just place the values in an existing SO instance
I'm just going to say i completely agree with Fen, to me, its trying to fit a round peg in a square hole
i think im just gonna leave level data alone for a while
you feed it string and an instance of an SO
im nowhere near that point yet i was just wondering if it was possible
You should distinguish unity serialization from your own serialization
An object is serializable by Unity if the game engine can understand how to turn it into data and then get the original object back
A good example of the difference: dictionaries
i just remembered in my old game i actually had that system using newtonsoft,json
so i might just do that again
Json.NET can handle dictionaries just fine
(and with a little finagling, you can even do dictionaries with complex key types)
Unity has no clue what to do with a dictionary
I used to think that ScriptableObjects made sense for this, because they kind of look right
they're serialized, and you make files (assets) out of them
but you don't create and store new ones at runtime
anyway```cs
public static T Circle_GetOneComponent<T>(Vector3 position, float Radius, int layermask = -5)
=> Physics2D
.OverlapCircleAll(position, Radius, layermask)
.Select(x => x.GetComponent<T>())
.FirstOrDefault();```why is one Overlap hitting and the other doesnt? 
maybe it's just on the edge
i don't know how well the visual lines up with the actual physics query
How do I reset a scene upon death but keep the lives reduced instead of resetting?
Yeah same, I have used them that way if I have to. But these days I definitely prefer for them to be used for informational structures and keeping my user and saved level data stored separately
you need to store that data outside of the scene itself
one option: use DontDestroyOnLoad to move an object into a special scene that never unloads
another option: make the lives counter static, so that it's not tied to a specific object
I use them for my settings and configuration systems right now. They define what settings exist, what they're called, what their limits are, etc.
and for settings, the actual data lives in them to
(configurations aren't global settings; they're for customizing specific things)
so their data actually lives elsewhere
but when serializing, I pull that data out and create a plain old C# object that gets serialized
it have same range and buildings have same displacement, idk why it not hitting though
Looks different to me. Compare where the circle touches the building
good luck hand-editing your settings file...
what is this notation with the arrow?
rotation? wait im iliterate lol
it would be if it looked like this
var wat = (x) => x * 2;
That's just an expression-bodied member
does the arrow replace the brackets or
an expression-bodied method, specifically
It lets you write a method as a single expression
ah yeas
So yeah, it's an alternative to writing a method made up of many statements
You can also make expression-bodied properties
it's called expression body
public int Property => 3;
public int Method() => 3;
I like mixing this with switch expressions!
what is this event system that keeps showing up in my hierarchy
public int PlayerCount => mode switch {
GameMode.SinglePlayer => 1,
GameMode.Duel => 2,
GameMode.FortniteGaming => 100
};
the EventSystem turns your input into information that the UI system can understand
oh right
it tells buttons when they're getting clicked and keeps track of the currently selected game object
i havent done anaything with that yet but i feel like i'll have to soon
cus im using controllers
of course, nowdays, GameMode would probably just be a scriptable object
public int PlayerCount => currentMode.playerCount;
There are a few pain points with controller input
notably, it's really easy to just...deselect
and then be trapped forever
thats great
a common fix is to have a component whose job is to just select something
void Update() {
if (!EventSystem.current.currentSelectedGameObject) {
var target = FindFirstObjectByType<Selectable>();
EventSystem.current.currentSelectedGameObject = target;
}
}
I do things more granularly, but the same idea holds
each of my menu screens knows if it's the "active" one and is responsible for selecting something if necessary
hey Fen! what if you have two active menu screens that both need to be usable at the same time?
🫠
i should think about that
then you have a problem with mouse input: the selected object looks a lot like the hovered object, which is confusing
you see two things highlighted at once
I've played around with auto-selecting whatever is under the cursor, but that can be unintuitive if you're using the keyboard to adjust sliders while clicking around menus
i mean luckily the menus im making are gonna be super simple and only have like 3 buttons
Me too! Its comforting knowing someone else is doing it this way too
I was originally deserializing directly into the type that actually holds the runtime data, but then I realized I'd have to replace the existing instance with a new one
which was a hassle because I'd have to copy over some other information (like lists of listeners for each config item)