#💻┃code-beginner
1 messages · Page 405 of 1
and very little is completely "done by yourself"
I read articles about the "wave function collapse" scheme before implementing it; i didn't invent it on my own
so its okay to watch tutorials and copy what they do/write?
since i can not think of anything writing it from scratch sadly lol
i wouldnt even know how to throw tiles from a tilemap into the map
start by just figuring out how to fill an area in a tilemap with one tile
then pick tiles randomly
then start doing more complicated things
90% of coders basically are just good Googlers that can make different code together 🤣🤣🤣
You are suffering from imposter syndrome
meaning what
not even pros who havent made a procedural world before know how to do a procedural generated world without specifically studying it by googling tutorials and stuff for it and copying stuff
i think ill just break it down to small pieces and ask chatgpt to explain to me this small steps, then try to write it myself
like i just asked chatgpt "how to create a chunk"
then next will be "how to set tiles from tilemaps into chunks"
and so on
i would not advise using a spam generator to write your game
its better to just look up a tutorial. there are many procedural generation tutorials
okay or this then
hi guys can someone explain me something
Why is this invalud? Please excuse my ineptitude
f(MathF.Abs(CatBody.velocity.x)>) <= 0.1)
how can i add sound to an animation on unity?
add an audio component and then reference it in the script, i think. you should watch a youtube video on it
Because you have a reandom nonsensical >) in it
>) <=
what do you think this does?
fuck my bad LOL
guys how do i fix this 😵
you can't, really
stop trying to use field initializers
the version of C# that Unity uses doesn't allow for struct field initializers
they can only start out with the default value
Field initializer is using = ... directly on fields
okay thats not an issue, ig ill just pass a default value in the constructor
Note that in the C# version Unity uses, structs cannot have default parameterless constructors
can structs be seralized in the editor?
Is it possible to define spawn points for the input manager?
yes, subject to the normal serialization rules
ty
Not in the input manager, no. Elsewhere
Meaning for the player joining
Would you happen to know where that would be?
Oh right okay
Thanks
it'll send a message to MonoBehaviours on the same game object as itself
Thanks alot
idk i feel like giving up to even start making my game
i learned so much hours of c#, but chatgpt aswell as tutorials seem to be cheaty
Since i can copy, but not actually write or change stuff accordingly.
I would need help on like very meter of that developement lol. Damn game dev is hard and frustrating. Hm.
Theres no "cheating" as long as you're learning and having fun who cares
How do I do a "Please press a key" thing for rebinding controls? I tried googling but only found outdated information about it being impossible.
nothing good in life is ever easy, my friend. keep trying hard. use your head, do your own reserach, and never rely on videos to copy and paste stuff. you got this
there's probably a command in unity to find the key being pressed. or you could be a madman and have a massive if statement xD
I know there's "Input.GetKeyDown" but how do I use it? And how do I make the environment that allows it to listen for the keypress?
Dlich, if you're reading this, I fixed it.
The function was just poorly written, so I started over and now it works (it seems so, at least)
although you can do key rebinding using the old inputsystem. the new input system is very much more suited to that
I want to use the new one but I don't really know my way around. I haven't found what the way is to find how to do it.
I will assume I might have to start a coroutine on button click, then stop it once it captured and set the key as well as the image, or default to the previous key on leave?
Thanks!
Do I have to separately install something for it?
It talks about "Input System Package" and IIRC packages are installable optional content.
yes, in the package mange look for tyhe Input System package
That is it
The old one is not a package
You can tell because anything that says Input SYSTEM is the new one. The old is the Input class and InputManager class
I guess also that the description says "a new input system"
Thank you!
Please learn to read what is on your screen
The old system is built into the editor, and configured from the "Input Manager" section of the project settings
I just wanted to make sure, sorry about that.
I had some experiences of falsely assuming which led to some projects I spent a long time on being permanently ruined, so I make extra effort to avoid misunderstandings.
@pliant oyster That sounds like you are not using Version Control.
Stop everything and set that up now
not assuming is very, very good practice, just dont take it too far
Will do that
you should be able to hit your project with a sledgehammer without any risk of losing your work
i can't imagine not using version control nowadays
hello
i have a basic trouble
consider i have a raw image in UI
at position x = 0
position y = 0
and height and widht are equally 50
now i want to use my mouse scroll to increase or decrease this size and width equally
and your question is?
suppose i got the mouse up and down values
So you want to zoom?
does anyone have any information on how i can set a drop down in a menu to translate my game from english to other languages please
the dropdown menu is the least of your concerns. Look into the localization package https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/QuickStartGuideWithVariants.html
Store the original width and height. Multiply those by the scroll value.
then calculate a % increase/ decrease based on current sizes
Sending it all in one message would probably solve it, instead of hitting Enter every five words.
Shift+Enter to add a newline without sending the message
here is something i am doing
lots of code changes to pick up the languages i guess
ok will care next time
isnt there anything like a math equation from which i can do the calculation
i am pretty bad with such stuff
From what I was thinking
i thought of taking ratio by ratio value and then increase decrease that to generate the new zoom value
calculating a % is pretty basic math
sorry but real noob with maths
google is your friend
arent you guys friends as well
we are here to point you in the right direction, not take you by the hand to cross the street
🙃
btw, if you want to continue with game dev you are going to have to get pretty good with math pretty damn quick otherwise your life is going to be miserable
yea
i know right
tho i am developing a sort of tool right now rather than a game
as you can see here
Bro I've made rpgs and never needed math
big doubt
You don't need math knowledge for gamedev 90% OF THE TIME
no, wrong, 99% of ANY dev is math
At worst you just copy paste copy frommonline
that ain't dev and if you think it is you are very much mistaken
I made a old school Zelda clone for college nevervneeded any crazy math
i agree
ah, so now we've gone from 'no math' to 'no crazy math' which is it?
i usually serialize my animations and using encryption algorithms
You don't need to know trig or whatever unless you are making a particle system or physics or whatever and 90% of it is copy paste
for the best efficiency you need the best way to compute stuff
there maths come in handy
Dealing and Quaternions and stuff as well
i think i give up at this point. I have my dream game in mind, but then its the question if others would even enjoy it. Unity and coding seem to be fun, but its frustrating to be just a copy/paster from the very beginning not knowing how/if it affects your game. I guess it would take months or years to make a beginner 2d game. Like i know what i want to create/do, but there is not even an idea of how to put it into the game code wise. Im also bad at designing graphics and dont want to use open source ones that everyone uses. Guess its just not meant to be at this point and i should maybe do something else. Code small projects with c# general or just focus on one sub-part of game dev like creating pixel art and selling.
Thanks for all your help guys. Rip.
i added a debug for my Keyboard.current.leftMouse.isPressed and for some reason when I click my mouse once it prints 7 times.. why is that?
I only want it to print once
because 7 frames elapsed
wait so it registers it every frame? not just the frame i pressed it in?
Update runs every frame
you're cehcking if the button is currently held down with that code
how do i make it check only if the button is pressed once
if you want only the initial press, use Keyboard.current.leftMouse.wasPressedThisFrame
You cannot even code a simple for loop without knowing math
thank you!
by the way; you mean Mouse.current.leftMouse.wasPressedThisFrame, not Keyboard.current.leftButton.wasPressedThisFrame
Bro if you consider 5+5 "math worth considering" idk what to tell you
If you don't think 5+5 is math...
math is math, whether it's 1+1 or quatrilateral equations, it's all math
Yes its "math" but if thats something that you consider worth mentionjng...
People ask if you need to know "math" they are asking if they need to know physics, not basic pemdas
i wrote 4,000 lines of code just to make a file browser that opens and browse assets
and you cant even imagine what algorithms i used in that process
you have to agree
if you are not good with maths
you cannot even do all these for loops
you cannot know that. OP, who started this, did not know how to calculate a %
It's important to mention, a tool or asset store creator creating tools for devs, understanding optimization, math, structures etc is even more important. Gamedevs will rely on your tools (and, in a way, expertise) to make their games. And to avoid a lot of support calls, the more you can do early on the better.
I had to brush up on three.js euler to quaternion and deconstructing/reconstructing matrixs this week for a webAR thing. But it's good to learn.
I'll also go against the grain and say to ask AI about it from time to time. Don't take it as valid, but it can help nudge you in the right direction if you don't have a lot of time to really breakdown the subject.
Thanks for the advise
the first part looks like the free browser asset on unity asset store 🤔
What tutorial did you use if any? I am also wanting to do something similiar for players to upload custom emotes in my game
just a tool for studying game files
I disagree, if i wanted to recommend physics I'd recommend physics. Telling someone trying to learn percentages to create gamedev tools that they need to get more comfortable with math is not only completely appropriate, but way more on point than this side tangent. Imo.
I dont use tutorials
just experience
also I am 18
so you ripped off the code just say so lol
ripped off???
yo we can have a debate on this if you say ripped off
That is awesome, but make sure you are doing the best coding practices
could've at least changed the UI of it so I wouldnt recognize it lol
🍿
you dont even know how much it takes to build one
🤣
makes me question how much of this is your code..
Actually, I do, having built many
i wasnt talking about this file browser
if a gameobject is active then the Start() function runs, then i make it inactive then i set it to active will the Start() function run again? or does it run only on the first frame?
No.
the browser i use to itterate between files i loaded from the filebrowser
The Start message only gets sent to a component once.
i was talking about that
Only the first frame
ah thats disappointing
OnEnable gets sent many times, though (:
Note that OnEnable gets called immediately after Awake -- and not alongside Start
You could've been a bit more clear instead of claiming 4000 lines as some kind of flex lol
(assuming that the component is enabled when it gets instantiated)
yoooo
i can show proof as my script
I just thought it was funny we dont have to prove anything. lets moveon
take a look at it
html and css don't requre that much for a simple front end site, unless you did something wrong
thank you! that solves the issue then

yeah I wish I wouldn't have seen that lol
🥲
you guys literally went against me
what wrong did i do?
nobody is against you my guy
You said "I made a file browser" I saw the two matched, thought it was funny.. let move on lol
nobody is trying to put you down but, if math is a problem for you I seriously suggest you spend some time worknig on that
Honestly you worked hard, it is visible in the code. But if you knew a bit more it would be easier on you, like spamming if statements is never good my man
I wouldn't worry about it too much, we are all somewhere on our journey, and gotta pick which path in front of us is the most interesting (and avoid those that are distracting)
on it
i should point out that this is obviously an interface for an asset ripper
really?
studying game files i said
not a ripper
A very poor euphemism
It's using UAE to extract data from a built Unity game. All of the code is copy-pasted logic to display different kinds of Unity assets.
You cannot get help about it here
yea sorry
stiches a bunch of assets together phew I wrote 4000 lines of this amazing code, math is hard
it's mostly copy-pasted logic with a few unique lines for each kind of asset
😕
i did rather not hear stuff about any effort i did
thanks for that
maybe don't claim 4000 lines as some kind of impressive feat, I wouldn't have been tempted to roast the statement lol
you're the one barging in and asserting your skill, so...
🙂
to answer your original question: calculate the ratio of the short side to the long side. use that to scale how quickly you change the short side's size
ok i backdown from my statement
i already figured it out
a 30x50 image, for example, would grow 60% as fast on the minor axis
thanks for the guide
I was just copying what you wrote, but yes
bye!
the thing i did like to know
how come do you know the name UAE?
this server simply doesn't allow you to discuss or get help with such things
along with modding in general
yea i know
my help was not related to modding rather development
so that's doesnt make any issues for me
dms allowed for you?
want to ask something
ive been trying to get unity (this version in particular because it's the one i need for an ultrakill level editor kit) and it keeps getting stuck in the validation stage of the editor application, i've searched online and tried solutions i found but none worked. does anyone have any idea on how i could fix this
Hey, so I am well aware that when you use the invoke method in unity, you will have to define what the name of the function. However, is there a way you can use the invoke method by executing one line of code instead of calling a function?
You mean a delegate? No
If you want an easier time combine Invoke with nameof to avoid confusion with magic strings
delegate? never heard of it. What is it and how do you use it?
I set up the new input system like the earlier linked tutorial said, now how do I capture the user's input and tell the system "hey, the user is now using a custom keybind for this action"?
Well, what else do you mean then? Got an example?
hey guys. why cant i add the OnDrawGizmos callback to my MonoBehaviour?
you can, you just have to actually write the entire method signature
Here is an example of using an invoke function-> Invoke("NameOfFunction", time);
Now, what I want is to not create a method to use the invoke function, but instead I want to invoke
one line of code like this->Invoke(boolValue = true, time);
is there a way I can do this? My goal with this is to not create a useless function that executes only one line of code.
i dont get it in auto completion tho. its weird
but this did work
Sorry for the headache I might be about to drop...
I am trying to make a movement script and right now implementing a sprint function so that I can go faster if needed. However when I press shift I stop instead of speeding up like how I should. Below is my code and the component in the unity program.
!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.
I come from gamemaker, is it possible to create global variables, or have a variable be easily accessible by other scripts?
if a variable is public you can access it by getting a reference to the object that it is on
Ah thanks updated the message (Can't get the txt file away tho for some reason)
Hey can someone help me here #💻┃code-beginner message
Your if / else if / else logic is wrong.
your pseudo code makes no sense but it looks like you want a lambda method
Add some braces.
ok thank you, you have given me a clue
if (!sprinting)
if (grounded)
;
else if (!grounded)
;
else
;
if (grounded)
;
else if (!grounded)
;
I've re-indented it.
Notice how this is not what you intended.
C# does not care about indentation. That middle else is associated with the previous else if.
Alright I think I get u, what do you mean by add braces tho?
you know { }
yeah this is looking very python
if (!sprinting) {
// ...
} else {
// ...
}
just needs an attempted elif 😉
whitespace nightmares!
ok, so I have tried to use this lambda operator, and this is what I have tried Invoke(() => Debug.Log("bdjabdha"), 1f);and I am getting this error:
Invoke does not work like that.
Oh I see, it's because i for some reason don't really have any in the move player function and I should have them after every if/eklse/else if statement right?
MonoBehaviour.Invoke sends a message, optionally after a delay
This has nothing to do with System.Action.Invoke, which executes an action
System.Action foo = () => Debug.Log("Hi");
foo.Invoke();
Especially when you have nested if/else if/else statements, yes
It's very easy to lose track of what goes with what.
Note that your IDE's formatter will reveal this
I just pasted this into Rider, deleted the expressions (leaving only empty statements), and then auto-formatted it
ok and where do I set the time parameter?
Alright thank you I will see if I can get it to work now otherwise I will be back (prob will be anyway with someting else soon lol) but yea I really appreciate the help
A coroutine would be appropriate.
Calling Invoke() on an action runs it instantly. C# has no notion of "waiting"
IEnumerator Wait(System.Action callback, float delay ) {
yield return new WaitForSeconds(delay);
callback();
}
(you can simply use the () operator here)
@swift crag Def works now thank you so much!
do any of you guys know how to use JU
(being handled in #💻┃unity-talk )
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Quick question. In my roomManager script (https://gdl.space/kumejesuli.cs), I create a Room roomSave variable which I set to be the room we load. Later on I use this fact to load the roomSave to make a Restart mechanic. Everything works as intended, except for the fact that the roomSave is updated along with whatever it was saved as. I had this problem when I started learning javaScript, and this is caused by me saving the reference to that room, not the actual room's data. If there is a way to set roomSave to a COPY of whatever object we set it as, I'd be thankful to anyone who tells me. (I asked chatGPT and he broke everything, as always)
You need to be able to either:
- create a new Room that's a copy of an original
- serialize and deserialize your Room
(these are roughly the same thing)
you mean add a Room variable for every single room?
like, make every one a prefab?
What is a Room, exactly?
Is this a GameObject/some other unity object?
Show me the Room class.
question how do i learn C# like the most optimal way.
learn the basics, then try to figure out how to make simple scripts on your own, and look up small things if you get stuck
and where do i learn the basics
gpt suggests adding something like this
which could work, those are all the public variables we use
should I give it a go?
!learn will teach you C# in the context of Unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
tysm
note that GameObject[].Clone() is not a "deep copy". It just creates a new array with the same things in it.
You can Instantiate the entire room to create a new object. This may be appropriate.
However, this would break those children links
I would suggest trying to separate the mutable and non-mutable parts of Room
So, you've got that "interacted" field -- that changes as you play, right?
the second you make a move it changes. I mostly added that for debugging purposes in case the level is Clear'd instantly
If most of the Room stays the same, give it a "Restore" method that resets those mutable parts back to the defaults.
also, this wouldn't work because you can't construct a new MonoBehaviour
what changes is mostly the children array and all the data of everything inside it
well then that gets a lot more complicated!
I guess you could parent all of the rooms to an object and Instantiate the entire thing
would just making all rooms prefab variants of the main Room prefab an option? Or is this a cowardly approach
Hello! I'm using Graphics.DrawMeshNow but nothing is being drawn?
void Update()
{
foreach (var chunk in chunks)
{
// set first shader pass of the material
worldMaterial.SetPass(0);
// draw mesh at the origin
Graphics.DrawMeshNow(chunk.mesh, chunk.position * 16, Quaternion.identity);
}
}
Do you need to remember multiple rooms with connections to each other?
I'm unclear on the scope here.
When I put the mesh on a mesh renderer it renderers fine, but when I do this, it doesn't do anything.
No errors, either.
I just need a room with all it's properties stored in a variable in a way where I can recall it from that exact state it was saved in
That does not answer my question. Do you need to remember how rooms are connected together?
children is a field on Room, so...maybe you do?
rooms are not connected besides being on the rooms list in roomManager
You can instantiate all of your rooms (thus creating new ones) and use those for gameplay. When you restart, destroy the instances.
brb 2 mins
So can anyone help?
ok im back
I think I'd need to rewrite a bunch of my code
Why?
I don't quite understand, can you evaluate?
Room instanced = Instantiate(originalRoom);
This will copy the game object and all components on that game object, including the Room component.
Do I put this at the top in Room?
this would cause every room to copy itself, and every copy would copy itself, and ...
When the game starts, make a copy of your rooms. You will use these rooms to play the game.
When the game restarts, destroy those copies and make new ones.
so I should make an originalRooms array, add the rooms there
and then... hold on a second
why did i just get 44 errors when i opened my project??
There's a lot to change in the manager now
you got conflicts.. for (1) you have two scripts called InputActions.cs
wait, I already have an originalRooms array of rooms where I add each room on Awake
ok, @swift crag I think we can use the originalRooms array, as the only place it's used so far is adding all rooms to it on roomManager's Awake.
I set up the new input system like the earlier linked tutorial said, now how do I capture the user's input and tell the system "hey, the user is now using a custom keybind for this action"?
i deleted my old inputactions but now i have this error. i assume its because of conflicting class names but there arent any, theyre exactly the same so idk what the issue is
#🖱️┃input-system is where you should ask. There are also pinned resources you should check out
I thought maybe I could instantiate the originalRooms array's rooms on Start/Awake, swap their position on the array for the new instantiated ones, and then we'd have something to work with, but I see too many complications this would result in
Thank you very much!
man, why is this so weird
Is there a way to check if a navmesh has been built?
maybe you can check the bake data on a navmesh surface if its not null
nah, thats not naming conflicts, now its just a regular script error
Sorry I forgot to mention this, im building the navmesh at runtime for a generated maze, can I still check the bake data
yeah
!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.
Chicken, you been here a long time.. u dont haave any of those bookmarked by now?
i got hatebin memorized but that website only works half of the time for me 🤣
Niice lol
yeah same it used to be so good, it went bust outta nowhere
Is this the right way to nest coroutines?
https://paste.ofcode.org/9M8ywXDCiBfsanabp7Raa7
i couldnt say ive never nested a coroutine in a coroutine but im interested to see what other have to say
i fixed it by deleting the old script and re making it
nothing obviously wrong with that
public GameObject scrolluv;
void Update()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0f || Input.GetAxis("Mouse ScrollWheel") < 0f)
{
//Get the mouse position on the screen and send a raycast into the game world from that position.
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
//If something was hit, the RaycastHit2D.collider will not be null.
if (hit.collider != null && hit.transform.gameObject == scrolluv)
{
Debug.Log(hit.collider.name);
}
}
}```
i have this code to tell me if i am scrolling it tells me if the object i am scrolling on with my mouse is
but it doesnt work
it always displays the value even when my mouse is not hovering the 2d object
what does? this function doesnt return anything
What does it say it hit when not over the object?
it hit even when its not over the object
That is not what I asked
What does it say it hit?
The name. In the console
yes
the name in the console
it says it hit
when the mouse is not even at that point on screen
Please read what I am saying
What. Is. The. Name
FYI it would be more appropriate here to use Camera.main.ScreenPointToRay and Physics2D.GetRayIntersection
Physics2D.Raycast was designed for raycasts within the 2D world
seems like you have some object named "texture image"
There we go. You have an object called texture image
probably a background image or something
You could put that to ignore raycast layer
its not really a gameobject
but a 2d Ui raw image
Ui is still a gameobject....
Everything is a gameobject
sounds like you put a collider on a UI element which is a nono
yes i added a box collider2d
why
Well... remove that
so that when the ray collides it would return me that object
UI should not have a collider
UI elements automatically have their own detection
Use the event system for this
use the Pointer interface

ok let me remove the collider
now what to do?
using my cursor to point over a specific image and use scroll
if the cursor points on some other object and scroll
it should not affect anything and the void must return
Attach an EventTrigger component to your image
more like a image zoom in and zoom out
and set up the "OnScroll" event
i want the image to zoom when the mouse is scrolled onto it
or make your script implement IScrollHandler
let me do it
event trigger seems good to me
worked
thanks for the help
your the best
Yeah I had some sort of thing like this in mind, thank you for providing an example
Guys why the post process volume component doesn't affect my scene 💔
you gotta do this
also this is a code channel
Oh sorry
holy gamma batman
speak in full sentences, and remember this is a code channel.
I have a capsule collider
And a plane. More than one in fact!
is there a way i can scroll by clicking in the image
rather than dragging the viewport
the problem i am facing is that
i selected the image as the content in scroll rect and the borders as the viewport
the problem i am facing is that
i cant use scroll by clicking on the image
but i can use scroll by clicking on the viewport
any fixes
(Also sorry for my previous half sentences)
not a code issue, -> #📲┃ui-ux make sure the image has the target raycast bool ticked
ive been trying to get unity (this version in particular because it's the one i need for an ultrakill level editor kit) and it keeps getting stuck in the validation stage of the editor application, i've searched online and tried solutions i found but none worked. does anyone have any idea on how i could fix this
ok let me try
Not a code question, see in #💻┃unity-talk
oh mb
guys for me to run animation events do i have to have the component that has the function attached to the gameobject with the animator or is it okay if its from another object
It has to be attached to the same object as the Animator
oh that sucks
📃 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.
what in the world is going on?
!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.
I'm not sure how much it's really a code related issue. But here's the script I'm using for my DebugConsole.
You have some basic compile errors you need to resolve in your code
isnt this #💻┃code-beginner ??
Yes
welp
I'm explaining to you why you're seeing errors
can you help me find a soulotion?
I know this might be a silly area to ask but any chance anyone can help me with circuit analysis? Figured since most of you code it would be a good place to ask as most comp sci students take it
You would need to show your code if you want more specific help.
thats alright, 1s
wait nvm chat gpt just helped me
robot>human
I mean, sounds like ChatGPT actually got to see the code
ur saying robot isnt better then human?
You're in for a rough lesson
what
Is it a fair comparison if the robot gets to see the code and the human doesn't?
just wait until the robot gives you entirely incorrect information that you don't recognize as incorrect and nobody else is there to point out that it's incorrect
yes
ofcourse it is
in for a rude awakening
Living up to the name
No it is of course not. That is so stupid
im so sorry for saying that
ur saying i look like a troll?
kyro TV you have smt to say?
@orchid pewter Move on, please.
Okay, im sorry
Hello, I'm having problems displaying a scriptable object.
Item.cs scriptable object: https://pastebin.com/wPTb0GNQ
DisplayItem.cs my UI script that is attached to a parent container containing various UI elements related: https://pastebin.com/7AYTcENL
Errors in code: NOTE that none of my Debug.Logs display.
NullReferenceException: Object reference not set to an instance of an object
DisplayItem.UpdateUI () (at Assets/Scripts/DisplayItem.cs:28)
DisplayItem.Start () (at Assets/Scripts/DisplayItem.cs:20)
I made an Item 'Charcoal'. Picture in editor: https://jumpshare.com/s/pRkx8vrNxiXfYrqo8ioT
I've setup UI elements to display here along with buttons. The buttons have their On Click() function referencing DisplayItem.IncreaseQuantity() and DisplayItem.DecreaseQuantity().
Pics of my Hierarchy and Inspector of 'Item Line' which contains my 'DisplayItem' script: https://jumpshare.com/s/CqQZl0fLoYCshBoZCVgu
Hopefully I made it easy to navigate. It's my first time posting in here.
itemAmountText is null and is never assigned to anywhere
itemAmountText is null, for that exception
Ah 🦥
right but I'm assigning it on line 28 itemAmountText.text = item.itemQuantity.ToString(); I believe that would convert the Int variable from item class which is assigned 0 default. Am I misunderstanding something here?
no you are accessing its text property on that line, not assigning to that variable
you're assigning text, that isnt what the error is about
for future reference this
DisplayItem.UpdateUI () (at Assets/Scripts/DisplayItem.cs:28)
tells you exactly which script and line of code the exception occurs on
the variable is null so accessing its text property is causing the NullReferenceException
don't worry, when you figure out how to assign it, you'll end up with another because icon is also null. then after fixing that you'll have to do the same for craftingSize
I had those set to public and referenced before. I have no memory of making them private. My brain is super fried but it's fixed, thank you guys.
you can still make them private, they just need to be serialized. you can slap a [SerializeField] attribute on a private variable to be able to assign to it in the inspector. that way other objects cannot reassign the variables as well
So if I want my buttons to work to increase or decrease the amount I can't Serialize the Quantity right? Because then the buttons wouldn't be able to interact with the script? So in that specific case it would need to be public?
huh? your buttons would call the Increase and Decrease Quantity methods. as long as those are public they can be accessed by the button(s)
Ohhhhhhhhhhhhh I see now that makes sense. Thank you, I was looking at this like "How is this working???"
and public variables are serialized already. that's how they appear in the inspector
so is it just best practice to Serialize anything that you wouldn't want to be public? I may go back to the documentation on access container types.
i feel ur overcomplicating it.
probably
if you want something to be editable in the inspector but not accessible to other objects, then yes it will need to be private (or protected if you want to allow access to inherited classes) and you will need the SerializeField attribute on it. that attribute just makes non-public fields serialized since public fields are already serialized (if they are a type that can be serialized)
you use different protection for w/e the variable is needed for
public, private, static, [SerializeField] private, etc
best practice is to have no public fields at all though. use properties if you want other objects to have access
^ thats a big beginner mistake.. eeven me
That makes sense.
thats why u use private variables unless that variables needs accessed outside the class from somewhere
then if u need to expose a private variable for ease to you (assigning it for example) u can use the SerializeField attribute
its easy in the beginning to make everything public soo u feel like u have full control in the editor
u can also hide a public variable if u need to.
I feel like I went over all of this in the Create with code course and it's only now really sinking in. (I am a conversational learner though so that checks out). Thanks for your patients and explanations guys.
that eureka moment.. i call it a click moment
that happens alot... when ur learning.. usually delayed a bit after learning something lol 😅
w/ coding stuff makes more senes when u start implementing it hands on.. and some things u learn u dont really need to know until you do
before I started learning game dev full time it took me a long time before it clicked on how I can break down the game I want to make into approachable tasks which felt like a wall before I could start any project
but by doing more fun projects more things will click
absolutely agree, thats why i ended up with dozens of prototypes.. i may never use em but i learned alot from each one
I'm noticing something weird. Are scriptable objects supposed to be used as a save-load type thing? When I increase or decrease in play mode and then exit and reload it stays exactly where it left off. I assumed since everything else is temporary during play mode it would have set those values back.
Or is that a bug in editor?
saveload thing? not really they're just for storing data
yes, scriptable objects are supposed to not revert once play mode is ended. but in the built version, scriptable objects will revert to their original state.
youll have to do additional work to get scriptable objects to revert to their original state.
That's good to know. I haven't done any research on save/load. I assume I can do all this with export/import into a jason file but that interaction just threw me for a loop. I'll keep that in mind while I build, thanks again!
generally the process for save/load is to write to a file. this is up to you on how you'd like to do it.
if you publish to steam you can use steam's sdk to save player data. if your game is synced to an online network, thats an entirely new topic. the overall process is to write your own code to save/load to a file.
the file you save/load to can be plaintext for now, encrypted if you know what you're doing, or the overkill solution is to start your own db locally
in my current game I'm storing my stuff in plaintext 😦
speaking of.. is it bad to use scene indices over other methods like string names
id say scene indices are about as "hard coded" as string names
you can always re-order your scenes by accident but your scene names wont change
i need to use a cutscene now.. and id have to drop all these down a row
thats ridiculous
plus scene names are serialised like dictionaries anyw
i wonder if we can change scene directly based on a scene asset reference
i probably could use an array instead
im not sure i'll try that in a min
i wish it were that way but because of legacy code it will not happen
a list of scenes would be fine w/ me
scenes are built into the code
Use SceneAsset with if unity editor, then in onvalidate populate this array based on an array of SceneAsset
i just wrote a property drawer for a SceneAttribute that will draw a list of my scenes to choose from for a string variable. I think NaughtyAttributes probably has one of those as well
If it's a singleton you can just get the reference on demand
if you are trying to access the singleton, do it no sooner than in Start, especially if the singleton is initialized in Awake. you don't want the non-deterministic execution order of different objects to potentially fuck you over. but yeah you can also just access it on-demand rather than caching a reference to it in one of those initialization methods
rule of thumb is to do all self-initialization in Awake then wait until Start to access other components to ensure they are already properly initialized to the state you are expecting them to be in when you access them
And then when worst comes to worst WaitUntil() they are initialized
so is there a way to swap a sprites texture? i figured that it would be less time consuming for me to duplicate my sprite and change the texture than to create a whole new sprite and manually add all the "rules" to it
You can create a sprite object through code. That might be relevant.
I have not done that, though
Why dosent this get the bullet prefab?
well for starters, a prefab does not live in the scene so it wouldn't find it with the tag since that only checks the scene
The scene probably doesn't have a bullet object
This method returns the first GameObject it finds with the specified tag. If a scene contains multiple active GameObjects with the specified tag, there is no guarantee this method will return a specific GameObject.
and you can just drag the prefab into the slot in the inspector instead of using the Find call
Oh. but what about getting an prefab that there is none of in the scene?
Im doing this in another prefab
prefabs can reference other prefabs
I don't understand your question. It finds a scene object, not a prefab.
do i need to use another type of Instantiate because it says The Object you want to instantiate in null?
that means it was not assigned on whatever object you are using
You're probably referencing nothing
oh because of the old code i removed the prefab........
ah yeah, if you didn't remove that line in Start then you're overwriting the inspector assignment with null
do scripts interfere with one and other or do they stay separate? in other words do they share variables?
There are no "globals"
so x in one class will have nothing to do with x in another class
There are static members, which are part of the type itself, rather than part of a specific object.
public class Foo : MonoBehaviour {
private static int counter;
void Awake() {
counter++;
Debug.Log("This has run " + counter " + times");
}
}
This will count up every time Awake runs
In this case, only Foo is allowed to see counter. If counter was public, then anyone could access it with Foo.counter.
i was going to use the y-axis number from my movement script for a platform in my game, like if Y > Y_of_platform dont allow pass through
guess ill have to check the characters coordinates in the platforms script
If you need to be able to read a field from another object, you need to get a reference to it.
see the "Serialized references" section
i need a push in the right direction, i understand c# well enough to get into trouble, heres what im trying to do, i have a "character" which at the moment is just a 2d square with collider, i want to click and hold then drag then release to launch the character in the opposite direction where force is how far back you moved your mouse, bonus points if someone can show me how to put a movement limit on the mouse so there isnt "infinite" force
https://game.courses/mp - 2023 Multiplayer Mastery Course - Open NOW!
https://game.courses/birds - DOWNLOAD THE ART HERE
https://game.courses/bc - 2023 Game Programmer Course
https://prf.hn/l/BOo8AD1 - FREE Art from the Asset Store (Publisher of the Week)
Full tutorial to build a Unity game. Learn how to write code, deal with physics, sprites, ...
check this out.. he basically does that exact thing
Does anyone know how to enable text wrapping in an editor script for a TextArea? Is this even possible?
My reorderableList.drawElementCallback is kind of messy but I can provide it if necessary. The offending line is this one, I believe:
element.dialogueText = EditorGUI.TextArea(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight * 3), element.dialogueText);
Or maybe something other than a TextArea would be better?
#↕️┃editor-extensions
but also, just pass it a GUIStyle that has your preferred style settings assigned
Oh dang I didn't see that channel, thanks. It looks like .wordWrap might be it! Appreciated. *Very easy: EditorStyles.textField.wordWrap = true;
when the player interacts with the crate it is supposed to make a sound but it dosent here is the code and inspector ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class crateMoveScript : MonoBehaviour
{
public GameObject crate, crateText;
public AudioSource pickup;
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
crateText.SetActive(true);
if(Input.GetKey(KeyCode.E)){
crateText.SetActive(false);
crate.SetActive(false);
pickup.Play();
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
crateText.SetActive(false);
}```
is the camera colliding with that object?
i can still interact with the object its just the sound not playing when i interact with it
ah, then that is likely due to you disabling the object that the AudioSource component is attached to
ohh wait i didnt think about that lol
so ill make an empty game object with the sound that dosent get disabled?
Use an audio manager and pass the clip to it or deal with it all in the audio manager class
ok
or just separate the audiosource from the part that gets disabled. or use the AudioSource.PlayClipAtPoint method
honestly though, the way you are handling interactions isn't exactly ideal in the first place anyway
it worked ty
yeah i know this is my first game
I'm procedurally generating walls for a maze, and I'm trying to put materials on them but I don't know how to fix the stretched look of the wall materials
procedurally generate UVs as well
or use a triplanar shader
or set the texture scale procedurally
how would I do this when I instansiate the prefab
what prefab are you instantiating
if it's a prefab, just set it up properly in the first place
I have a wall prefab and I scale it to create the walls
it has a material on it
and when I scale the wall prefab the material looks stretched
then as mentioned, set the texture scale on the Renderer's material at the same time
okay thank you ill try that
What's the best way to add a Singleton to the project?
I created a property and an Empty GameObject with my singleton script and added it in the Inspector, but I'm not sure if there's a better way to do it
Didn't want to implement a threadsafe Singleton in C# so I had to go with Monobehaviour
if it is a MonoBehaviour then it has to be attached to a gameobject in some scene in order to actually be set up correctly
though you could theoretically lazy load it if you don't need to configure anything in the inspector. This is what I did for a singleton implementation, I just null check the backing field for my Instance property, spawn a new gameobject then add the component
https://github.com/boxfriend/Utils/blob/master/com.boxfriend.utils/Runtime/Utils/SingletonBehaviour.cs#L14
Tbh, I might not be on the level enough to understand this 😅
MAybe I should stick to keeping things in GameObjects
there's nothing really special or advanced happening here, it's just a property with an explicit backing field, it checks if that backing field is null when accessing the getter for the property, if the backing field is null is just creates a new gameobject using its constructor, then calls AddComponent. the only "high level" thing going on in the code i linked is that it is a generic class that I use for multiple singletons to inherit from. but if you just replace T in that code with the name of your class that you've turned into a singleton then it may make more sense to you
yeah, new GameObject() just creates a new empty gameobject in the currently active scene
So I could just, maybe, copy your Singleton pattern and extend it into my Singleton classes? 👀
you could just copy that entire class and drop it into your project. then just inherit from SingletonBehaviour<YourClassType> instead of MonoBehaviour and you'll be good to go. however it's currently set up to only call DontDestroyOnLoad on it if you create it in the inspector and specifically assign true to that field
this code is meant to load a scene, and then run a script in that scene called "MazeFloorManager"
But problem is that when i use this bit of script, it doesn't run the first time, but only the second time. What happens is that the first time it runs, the scene is loaded, and the second time, the next part of the script runs. I tried rmoving the "async" load but it doesn't change anything.
How can I load the scene and then immediately start using it?
is the object destroyed where the script is attached when the scene loads
if thats the case then add this to awake: DontDestroyOnLoad(this);
That second if is always going to be false when run the first time.
Scenes can't load that fast
Hello, when assign the option to dropdown in Start(), how can i change the label text? So, the text of that option is long, when that option is selected, I want to display a shorter text instead, not the entire string of that option. Thanks.
how would you do this, then?
I would make a coroutine that waits until the scene is loaded, or put an object with a script in the second scene and handle it from that Awake()
thanks!
Should I leave my UI scripts as a canvas component?
Is there a rule for this kind of things?
I put mine inside a collider that is a child object of my canvas
change the Overflow mode on the Label textmeshpro, if I understood your question correctly
why is a collider child of a canvas 🤔
Why wouldn't it be? 🤔
I need to do UI operations on it so I put a collider to detect clicks
colliders don't belong in canvases or UI
That was my reasoning lol
You do not need a collider to detect clicks
bad
And ui should not have colliders
collider is for physics, UI should not have physics
I'm not sure if I'm the worst Unity coder that's ever existed cause I keep making dumb stuff like this 🤣
EventSystem is how you want to detect UI
inspector only solution they have EventTrigger, in code you can use the interface or the raycast from the event system itself
Interesting
I'll see to it once I unbreak my code 😃 👍
I think I have that implemented already
well then why are you using colliders on ui 😆
Can I drag UI with this as well?
I was using raycast to detect collisions
So I could drag my cards around
look on the left
Not sure if it's needed tho 😆
the example goes hard on this one but you get the point lol
better more than less
some scripts need to go on the UI element itself unfortunately for these to work
im not a fan of stuffing scripts in UI, ofc if its a runtime created UI element you have no choice also
I'm so scared of my entire code breaking after I make these changes 😆
Oh well
It's 10:00 PM
That's a problem for future me
maybe practice on a separate smaller test project
before you convert, so you familiarize how it actually is working
what's going on with my UI when I change the colour? It's just a new image inside a canvas.
this is a code channel
Were you gonna.... say what you need help with?
Usually words are best, but ok
It depends on how you move, but you could do a second raycase angled forward, and check the dot product of the normal of the surface against Vector3.Up. if it is under a threashold, you can move up it, because the slope is gentle enough.
If over the threshold, just don't even allow movement in that direction
for a 2d game should i use 2d render pipeline or 2d universal
trying to make a game in 2 weeks with no coding experience
Something weird is happening, as you can see in the inspector, the value is 0
But when I debug the same variable, it debugs 1, any idea why?
nameText.text = "Qty x" + (UpgradesManager.Instance.largeTrucksOwned).ToString(); Debug.Log("Large " + UpgradesManager.Instance.largeTrucksOwned);
2D URP is better graphically and if I am right, performance-wise too.
alr ty
Two different instances most likely
Ahhh
I think I figured it out FacePalm You were right, I did +1 to the other instance
I'm dumb
Since it's a Singleton isn't it really bad for you to have two copies?
Something is wrong
Yeah, I just added this too
if (Instance == null) { Instance = this; } else { Destroy(gameObject); }
I was testing something and forgot to delete that line 😭
Ah, your Singleton implementation was not correct 👌
It was an issue that was happening when I was resetting everything, it was creating another instance.
Yeahh, I added it but commented it xD Forgot to uncomment it
How do you rotate a canvas ui image gameobject with recttransform? I'm currently in 2d
do I use .rotate or .localrotation or .rotation?
in these pictures, neither of the Z rotate is 90
I think you're getting confused between euler angles and Quaternions
Your logs are printing the Quaternion
using unitys new input system, through code, how would i detect each scroll up or down, all i can find is how to get whether your currently scrolling up or down, but i want when you scroll one scroll wheel increment if that makes sense??
not tested but...
If you create an InputAction for the scroll wheel and subscribe to the performed delegate it should give you a callback on each change
hey guys im trying to send some parameters through a string with animations but i get wrong format.
for (int i = 0; i < _val.Length; i++) {
print(_val[i]);
}
float _damage = float.Parse(_val[(int)AttackParameter.Damage]);
float _knockback = float.Parse(_val[(int)AttackParameter.Knockback]);
specifically on _damage = and _knockback =
it prints the correct values
the values that i input are 1.0_1.0 etc.
do you know what float.parse does ?
depending on your computer language/region setup you may need to use the Invarient culture for the parse
ok so string only contains "1.0" yea?
well say your computer is set to Spanish.
Spanish uses , as the decimal seperator so 1.0 is invalid but 1,0 is correct.
InvarientCulture uses the US standard so 1.0 will always be correct on any computer
it is a parameter you can pass to float.Parse
go read the docs
wouldn't it still print instead of invalid format?
it would be just be 10 no?
is numberstyles.none the US one?
no. TryParse would return false. parse, iirc, returns NAN
im working on a unity 3d game to run on google cardboard. when I run the game on my pc it works fine, but when i build and run on my phone the camera/player are in a different position
how can i fix this?
this seems more of an #🥽┃virtual-reality question
sorryy
what is your local culture. Is comma used as a thousands seperator?
im in US.
but wouldn't it be whatever is being used on dotnet fiddle ?
i figured it out
would also try to be sure the values passed were even correct
var dmgVal = _val[(int)AttackParameter.Damage];
var knockVal = _val[(int)AttackParameter.Knockback];
Debug.Log($"dmg val: {dmgVal} knock val: {knockVal}");
float _damage = float.Parse(dmgVal);
float _knockback = float.Parse(knockVal);```
i had to use system.globalisation
then it gave me the variables
also i used some wrong values 1.0f_1.0f
but i fixed it now and it works correctly
you had f inside?
This code snippets works flawlessly on PC Build and WebGL Build but it causes the object to spasm out as if it got fits instead of clean rotation on mobile and this only happens when the object has to rotate, after the turning part is done and the object has to go straight, it goes normally:
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
Maybe Due to Frame Rate differences or?
https://unity.huh.how/lerp/wrong-lerp check this
Seems fine enough... apart from lerping from the present value to the destination, which means that the interpolation will slow as it approaches the end value and will only approach the it as a limit rather than ever reaching it.
Framerate differences could see it visually leaping in rotation, but it shouldn't flip back and forth or anything.
If it's spasming out though, maybe your input value direction is changing erratically?
Oh, so basically using a smoothening value?
I don't think the direction value changes erratically as it does work on PC Build and WebGL But let me check just to be sure
oh the time.deltaTime.
would change it to similiar to example like
fraction = 0.3;
value = Mathf.Lerp(value, target, 1 - Mathf.Pow(fraction, Time.deltaTime * 10));```
just the t part is relevant
This is what I did
float smoothingFactor = 0.1f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));
Okay it's working normally on Editor, lemme make a Mobile Build and check
idk if that will fix your "spasm out" part, just fixes imprecision through diff framerates w lerp
Nope, didn't work. I guess it's not an issue with the rotation
Mute and watch, the music might be loud 😭
But yeah, this is happening. I think it's probably something to do with the waypoints breaking or something as it does continue on the path after doing that for a few seconds.
Weird that it only happens on Mobile
xD
are you making it follow points or something ?
Yeahh
can prob post the code to get better idea of what is going on
Okayyy
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It's a mess as I had less than a day to make this whole game 😭
It was either that or update xD And I am scared of using Update
coroutines are fine, but ideally you want to store them in vars to have more control of how many you run
or maybe stopping
I did ensure a check using the "outForDuty" boolean to check. And if there are no trucs to send out, it will just wait for 4 seconds again
I'm trying to look for bools but indeed you got a lot going on lol
I do have a lot of coroutines
Coroutines are always on the main thread
Ohhh
yeah they aren't true async/multithread
Ohh damn
tr.gameObject.SetActive(true);
tr.StartTrip();
tr.outForDuty = true;
idleTrucks.Remove(tr);
trucksOutForDuty.Add(tr);
This is what I do when I send a truck out for a trip
And I have a separate list for Idle Trucks
Lemme just change the order and see
Do you know what the framerate on the mobile build is, out of curiosity?
Well, I use BlueStacks Simulator
Let's see if I can see the FPS there.
I did test on my sis' phone and it had the issue, that's when I started trying to fix it using Bluestacks
It doesn't look like a performance issue to me
Yeah it isn't I capped FPS to 20 and it worked on PC
It's running on 59-60 on Bluestacks
I'll install Lunar Mobile Console and check logs ig
My Character animates his limbs but won't move, can anyone please help?
!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 direction is not changing rapidly
It's weird that it's happening, cuz nothing seems wrong 😭
It happens on PC too now, I just noticed although it's very very rare Hmmmm
If that speed of 5.0f is accurate, at <50 fps, the truck could overshoot it's destination each frame and get stuck in a correction loop for a bit (but probably not indefinitely)... It would also exhibit at higher fps if the truck's ... But it doesn't sound like any of that is the source of the problem at hand :/y position differs from that of a waypoints', and if they ever differ by more than the 0.1 unit threshold the truck may never be able to reach the waypoint
My only other thought is that it might somehow be trying to position itself towards two waypoints at once, like if two coroutines were competing... I don't see where that could be happening in the code, though. But in the video it sort of looks to me like the truck reaches it's first waypoint, and then the jittering begins as it turns towards it's next waypoint...
OHH
You might be right
Also is this odd for rotation?
I played the game frame by frame and notices the rotation value goes wild randomly
Are you looking a Quaternion values or Euler values?
The W in this, unsure what it is
That is a Quaternion. the values are basically meaningless to most humans
Makes sense 😭
My Character animates his limbs but won't move, can anyone please help?
I already posted the bot message for you on how to post code. Please read and follow it
Hmm I just noticed that it goes between negative and positive randomly when this happens. I had to screen record and view the video frame by frame 😭
My Character animates his limbs but won't move, can anyone please help?https://paste.ofcode.org/gqLDAs7qLUXzQgFAJErKVz
Why two transform.translate damn, you can combine them into one
you might like to Debig.Log the values you are passing into Translate
I'm making a game in Unity and there are vendors in my game and when I click on these vendors, the UI panel opens. This ui panel raycast target option is active but can still click on the seller behind it. With some sellers it doesn't click as I would like, but with others it does. How can I solve this problem?
that looks like a problem with your Direction calculation. Are you reading and acting on Euler angles?
He still won't move
Only this
float smoothingFactor = 0.1f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));
for rotation and then this for snapping them to right rotation when they stop:
if (transform.forward.z > 0.0f)
{
transform.rotation = Quaternion.Euler(0, 0, 0);
}
else
{
transform.rotation = Quaternion.Euler(0, 180, 0);
}
that does not show me how you calculate Direction
Hmm, maybe something wrong with RigidBody setup? Idk
OH RIGHT
Vector3 direction = (targetPosition - transform.position).normalized;
My character doesn't have a RigidBody.
what, exactly is this Debug showing?
The Direction Vector and the Current Targetting Waypoint from the code snippet that handles the position and rotation:
Vector3 direction = (targetPosition - transform.position).normalized;
Debug.Log("Direction: " + direction + " And Waypoint: " + waypoint);
transform.position += direction * speed * Time.deltaTime;
float smoothingFactor = 0.1f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));
That would tend to suggest that either targetPosition and/or transform.position are doing something odd, add both to the debug
There's no change in the targetPosition or the transform.position, only the Direction Vector.
I think that looks like the shooting and overcorrecting - it's ending up more than 0.1 units away from targetPosition each frame. You might clamp the change in position to the distance to targetPosition
Indeed. remove the .nomalize from direction. it's not needed anyway
Or that - that's better 😁
That didn't work, it made it worse 😭
show the console
i think yu didnt assigned anything in the animator.
This is what's happening when I remove .normalized
I have no idea what is going on there but those direction vectors make no sense based on the positions used
Yeah, it's weird. This issue randomly started, didn't have it before
What should I assign to the animator?
the only thing it can be is this
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));
it must be overcompensating
How about
Vector3 targetPosition = new Vector3(waypoint.position.x, transform.position.y, waypoint.position.z);
float distance;
while ((distance = Vector3.Distance(transform.position, targetPosition)) > 0.1f)
{
Vector3 direction = (targetPosition - transform.position).normalized;
transform.position += Vector3.ClampMagnitude(direction * speed * Time.deltaTime, distance);
float smoothingFactor = 0.1f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));
yield return null;
}
I added this after reporting the issue 😓
Let me try
there is an animator window. you have to add speed which you mentioned.
Wait this worked
It didn't happen
Let me make a mobile build and check
instead of two translates put one.
I tried altering the speed in Conditions and hes still stuck.
moveDirection = new Vector3(horizontal, 0, vertical).normalized;
transform.Translate(moveDirection * Time.deltaTime * speed, Space.World);
first of all you are checking vector3.zero and you are using ! so how you are altering speed.
Thank you so much! It worked on mobile too. So I just needed to add a clamp
Thank you too Steve!
I have an ! in here: "if (moveDirection != Vector3.zero)"
Also, altering speed where? In VS? in unity? In Gameplay?
I don't know why the truck was overshooting it's position at those framerates 🤷
But I'm happy it works 🍻 🥳
Yeahh, Unity engine do be weird.
ok i didnt checked that. there is problem in your animator window.
np, that is extremely odd behaviour, I'm still trying to figure out why
@elder raptor is speed set to to something other than 5.0 in the component inspector, out of curiosity?
Yeahh it is, been stuck on this one blocker for almost 2 hours pain
What do I do in there?
Yeah, it's double
10
add a float variable with name Speed.
What number should I put in it? Its currently set to 0
ah that'd be it... At 60 fps the truck would move ~.167 units per frame, so it'd have a hard time hitting that 0.1 units to targetPosition threshold 👍
Edit: though on second thought, 0.1 would be radius... It'd have to get within a 0.2 unit circle... so I still dunno 😕
public class newPlayerScript : MonoBehaviour
{
[SerializeField] Transform cameraProp;
[SerializeField] float sensitivity = 100f;
Vector2 look;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
look.x += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
look.y += Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
cameraProp.localRotation = Quaternion.Euler(-look.y, 0, 0);
transform.localRotation = Quaternion.Euler(0, look.x, 0);
}
}
``` theres no reason that this shouldnt move my camera up and down, i have the camera attached in unity, its only one button
Ohh this is weird. Never knew that actually mattered
leave it zero because you are changing it in code.
Is the camera a child of a object or?
its the child of my player object
He still won't go anywhere? Do I change the conditions or code?
Weird, lemme try
Yeah give me a min
Don't use two cameraprop.localRotations for each rotation, use this instead:
cameraProp.localRotation = Quaternion.Euler(-look.y, look.x, 0);
And if you saw, you did transform.localrotation for the second one xD So that might've been an issue too.
what should i have put instead?
And if you're attaching the script to the camera itself, you can do Camera.main or just do cameraProp = this;
Delete those two lines and use this:
cameraProp.localRotation = Quaternion.Euler(-look.y, look.x, 0);
void Update()
{
look.x += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
look.y += Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
cameraProp.localRotation = Quaternion.Euler(-look.y, look.x, 0);
}
This will be your update then.
In this Unity tutorial we're making the player go chop chop
Follow me on twitter: https://twitter.com/passivestar_
Join our Discord: https://discord.gg/pPHQ5HQ
this video confused me
watch it real quick @elder raptor
conditions.
Ah that's because he attached the script to the player
He was rotating the player sideways instead of only the camera
And only the camera for Vertical Moving
Changed the conditions and he's still stuck.
aha there we go
That's better if you're making a First Person Controller.
So use the code you wrote and attach it to the Player Object instead of the Camera and then attach the camera reference to it.
Okay good good
No problem
Good morning, i am using couple scripts for player movement and for the player camera, but they don't actually work. Is there a way to solve it?
Also the player movement's "rigidbody" flies away towards Z axis
make them work ?
It's a humanoid character right? If so, try using Character Controller to define Player Movement, it's way easier and less complex.
Character controller tutorial: https://www.youtube.com/watch?v=f473C43s8nE
Or just watch this tutorial.
xD
Basically, the player doesn't respond to commands, even after setting up the keys
Did you attach the script to a gameobject?
yes
And sharing your code(s) would help
the movement has a gameobject with the script and rigidbody
do you think we are mind readers? Supply some usable information, like your !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.
And always use proper debugs to figure out the issue first. ||I know I don't do that all the time but it is worth following xD||
In your case, you can add debugs to the Input.GetKey/GetKeyDown statements to see if the key clicks get register. If they do, then you can see if the movement functions get properly called, etc.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Move();
}
void Move()
{
float moveX = Input.GetAxis("Horizontal");
float moveZ = Input.GetAxis("Vertical");
Vector3 moveDirection = transform.right * moveX + transform.forward * moveZ;
rb.MovePosition(rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
}
}
Ok, so you should read Input in Update and consume it in FixedUpdate
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Move();
}
void Move()
{
float moveX = Input.GetAxis("Horizontal");
float moveZ = Input.GetAxis("Vertical");
Vector3 moveDirection = transform.right * moveX + transform.forward * moveZ;
rb.MovePosition(rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
}
}
And can you also show the Rigidbody settings?
Also, the firs thing to try is to increase movespeed all the time, sometimes it does move but like one pixel per frame
Can you show this in Inspector?
//like this?
void Update()
{
// Capture input in Update
moveX = Input.GetAxis("Horizontal");
moveZ = Input.GetAxis("Vertical");
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
// Rotate camera in Update for smoothness
LookAround();
}
void FixedUpdate()
{
// Consume input in FixedUpdate
Move();
}
@glossy turtle Are you still here?
sure
I meant in Hierarchy 😭 My bad
Create a thread if you want continuous discussion with them. Don't ping people repeatedly.
How can i do when it isn't touching it, the variables become true again?
sorry if my english is bad
OnCollisionExit2D
thanks
and then i created a gameobject in "player movement" for the camera
the input is all set as well
Try assigning the script the the Parent Player Object instead of the child
the movement?
Yeah the movement script
Yes
Remove it from the child, I usually make an Empty Game Object called Player that has the collider and rigidbody and Player mOvement script then make the Player Model the child of it.
i just did it
so, the movement is fixed and working, but now i will need the camera to be in the right position
//For the camera i'm using this script
public class CameraController : MonoBehaviour {
public float mouseSensitivity = 2f;
public Transform playerBody;
private float verticalLookRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
LookAround();
}
void LookAround()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
playerBody.Rotate(Vector3.up * mouseX);
verticalLookRotation -= mouseY;
verticalLookRotation = Mathf.Clamp(verticalLookRotation, -90f, 90f);
transform.localEulerAngles = Vector3.right * verticalLookRotation;
}
}
Ive heard it can be a good idea to go read someone elses code for a game, is there a game that is easy to understand of which you would suggest to check out if someone wanted to see how the coding is actually put into effect? Ive considered Hollow Knight but i dont know how to access its code
@elder raptor thanks for the help, i'm going to keep up with the animations
private ItemDatabaseObject database;
private void OnEnable()
{
#if UNITY_EDITOR
database = (ItemDatabaseObject)AssetDatabase.LoadAssetAtPath("Assets/Resources/Database.asset)",
typeof(ItemDatabaseObject));
Debug.Log(database);
#else
database = Resources.Load<ItemDatabaseObject>("Database");
#endif
}
the database returns null. Why is that?
You have a parenthesis ) in your file string
It worked right?
Oh my god. Thanks
it does
Yeah that's easy, just make it a child of the Parent Object and position it on the head and rotate it accordingly
but now i want to change between the main camera and the player camera, is there an easy way to do it?
Just enable the camera you want to see through and disable the camera you don't want to see through
ex
camera1.setActive("false");
camera2.setActive("true")';
Even better, if you can get reference of the camera as a Camera data type, you can just do .enabled = true/false.
public Camera camera1;
public Camera camera2;
void Switchcams()
{
camera1.enabled = false;
camera2.enabled = true;
}
i get the code, but i don't know where should i get it
for example, do i create a script for the cameras and put it in both cameras?
Make a script called CameraManager with a function to switch the cameras
like "switch cameras"
alright
And attach it to an Empty Game Object named Managers or Camera Manager or something
Technically you can do it in your Camera Controller script but it's not neat xD
"if it works don't touch it"
i did that code 4x before it even work
going to do it
Yeah but you might encounter issues in the future
A better philosophy would be 'If you don't understand it, don't do it'
probably
Good Job
why are you so negative?
He's a seasoned Coder, so he knows the negative sides of following shortcuts xD
It's obviously best not to have messy code and use AI generated snippets that you don't understand.
makes sence
it depends
i organize my code