#💻┃code-beginner
1 messages · Page 649 of 1
i cant figure this out and im disapointed https://paste.myst.rs/7z5cgp5j
a powerful website for storing and sharing text and code snippets. completely free and open source.
playerRb.AddForce(Vector3.up floatingForce, ForceMode.Acceleration);```
This doesn't make any sense
Did you forget the * or something
Lowk I wrote this at 3:00am I don’t even remember
yeah now that im looking back at it
Configure your !ide before continuing your project. Unity's console is not supposed to inform you of syntax errors. After that your issue is clear.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
does anyone know how I can make a newton's cradle
only the script side
or is there any asset or tutorial
i actually did get it somewhat working.. but not by using any type of realism
I understand how it should be done but its too complicated for something for simple
yeah same
swapping force between the balls colliding
mmhmm thats how i did it as well
but it wont work either 😢 it will break when you pull 2 balls
i almost got it working with realistic physics.. but it slows down way too fast
to make it anything like a real craddle u need to hand-hold it
basically write a controller that handles everything
it took me 3 hours 😢
the collisions, the forces, etc
yeah
oh heck no.. it took me about a week
oh okay XD
i cant find the original tho... just the clip
no worries
found it
im cheating by adding forces to the last balls
if i can find the script/setup i'll share it too
Fixed the script and I gotta fix my ide cause it ain’t showing but my low grav script works now so we chillin
Hey everyone!
In this video,
I have just tested the Hinge Joint Component provided by Unity Engine to Simulate Newton's Cradle, But since Unity Engine is not a Physics Simulation Engine, It doesn't simulate it correctly!
If you want to make your own game then make sure to check my Unity Engine Series:
https://youtube.com/playlist?list=PLrtqd9j...
Trust me when I say that setting up your ide to work is going to help you a ton
I had it set up in the past but I had to hit a factory reset
And I’m trying a new scripting app
Im used to VS Code but I’m trying Microsoft visual studio
good news, studio is easier to setup than code
thank you 🙂 it would be very appriciated
lol.. made it 3 years ago... apparently my organization skills weren't that great back then..
i know its on github somewhere just can't find it 😅
hewp me i just started
check the pinned content..
Hey guys So I'm making a game that transitions between levels, based on time. The visual scene is the same just the spawning objects frequency and pattern changes. I'm a complete begineer, should I setup a state machine for this?
sounds like a good use of a statemachine 👍
Okk
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://hastebin.com/share/borekemuci.cpp
It is code of my transfer between scenes
https://hastebin.com/share/icovusucut.csharp
It is code of my cutscene. We need to method of DestroyZombie
I want to transfer data from one scene to another. For example, I want to make it so that when the DestroyZombie method occurs, then in another scene there is a debug.log stating that this method occurred.
Help, please, I watch guides, but it didn't help me
There are many ways to "keep data" through scenes. If its a MonoBehaviour instance, you can use DontDestroyOnLoad() to make the gameobject never be destroyed on scene change.
You can also keep data in some other class instance and utilize static (e.g. static fields in a class to keep important data or have some class instance be passed to all loaded scenes)
Can also use additive scene loading to keep some scenes always loaded but remove/add some others.
the most mainstream method though is via ScriptableObjects
i like additive scenes
they are talking about storing data through an SO
hm k
since SO do not erase their data until the game is run again. (they revert back to the original value game was build with)
In Unity editor they don't reset themselves
Shared references (like current level or game mode)
Hello! any tips or tutorial how can i make a map rotation like this?
curved shader
thanks guys, i found it ♥
Learn how to bend your game world using Unity's Shader Graph to look like Animal Crossing visuals.
The Ultimate 2D & 3D Shader Graph Course: https://www.udemy.com/course/the-ultimate-2d-3d-shader-graph-vfx-unity-course/?referralCode=AA34C472F6CB6B86DE75
00:00 Intro
00:30 The Ultimate 2D & 3D Shader Graph Course Trailer
01:12 Setting up the scen...
Animal Corssing
12k views too
binary lunar makes really awesome content. how comes no one told him about the typo
Maybe he's been told and he doesn't care/ hasn't changed it
Maybe no one noticed it until you, just now. Well done, have a gold star ⭐
Welcome to Code Parade! This is where I'll upload interesting projects and experiments that I do for fun. Topics will usually involve games, machine learning, algorithms, fractals, or any other topics I find interesting. I usually include some explanations, and sometimes tutorials. If you have any ideas for projects, especially machine learn...
this guy has some pretty good dev-logs speakin on all sorts of non-euclidean geo
Carwash trying to be funny
People commenting about the typo in the comments is good for The Algorithm™️
SEO too
Hello I dont know if anyone can tell me why my console statements look so strange now, they've all become really hard to read heres an example:
Unable to find a valid spawn position after multiple attempts.
0x00007ff60f849f0d (Unity) StackWalker::GetCurrentCallstack
0x00007ff60f850be9 (Unity) StackWalker::ShowCallstack
0x00007ff6107b7a83 (Unity) GetStacktrace
0x00007ff610e562fd (Unity) DebugStringToFile
0x00007ff60e90a172 (Unity)
The actual log is too long to post in a discord message but follows the same trend
did you change one of these ?
or maybe something else
Not intentionally, in all honesty I just got a new dog and hes taken to running across my keyboard like a maniac so theres a decent chance hes done something, where can I find that setting?
ohh sorry it got cropped lol yeah the 3 dots menu on the console
check there but doubt if it was a keyboard mash could've been a shortcut for something else.
Theyre all set to full so it looks like thats the case
ahh maybe then yea
Ok interesting update that seems to be it but whenever I enter playmode it reverts to full
Hahha nope got it I was just in playmode when I changed it the first time and didnt notice
Thanks for your help thats been driving me insane and the knowledge to identify that so quick is impressive
i highly highly recommend to set up your editor in a way that it changes colour when you are in playmode, it helps so much
Preferences > Colors > Playmode tint
Oh that’s a great tip Thankyou
How can i change the Fast sRGB? its only get but not set
never mind i found a way
oh wait that was only for editor
anyone know?
yeah i dont think there are any ways
Changing that at runtime is probably not possible. Not sure why you would want to do that.
How do I correctly lock the mouse for first person in web? we've set CursorLockMode.Locked but it still doesn't capture the cursor..
ohh ok it was white on white..
some browsers you have to click inside the webgl/iframe iirc
to reach the point with fp controls, we have the player click on a START button so I think that's covered?
is this happening just on webgl or also on regular build ?
on regular build its a-ok
So I have a small conundrum:
I have some visual effects that I want to play at specific times, but I'm having problems with setting the rotations for it
I found the timings for getting the rotations right, but the problem is that the effect plays late, and I don't know how to go about it
at least, in editor it does
here I have that purple slash effect
this one
and because I found the correct rotations through movement, idk how to "save" it, so I can play the effect earlier
is there a way to do this maybe?
if I play the effect earlier, then, because the effect is attached to the sword and the sword is in a different angle, the rotation will be different
show your !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
well this is a code channel
well yes
I need to make this work in code
I used animationevents until now
I need to find a way to write this into code
This is a help server. Jokes go elsewhere
Sorry, I didn't mean to annoy the mods
Your previous history here is nothing but being told there's no off topic. If you continue to just pop in to do so, you will be removed instead. Thanks.
I figured out a way in the end btw
I ended up pausing the game during attacks and copying the effect prefabs
not the best way, but it works
oh
where do i ask for asset store publishing help?
does unity have some form of dependency injection
not sure if its so hard to put 3 words into google "unity dependency injection"
yep, 'dragging references via the inspector'
you can get some libraries which will make all of that much more complicated if you want though
yeah I was kinda realizing it may not have been smart to go for a single monobehavior root for my player
I don't think that dependency injection will help you at all there
character controllers are inherently very coupled and quite complex
true, its just annoying having to pass around references through large hierarchies
if you have a bunch of non-movement code in there or something though, that's worth pulling out
yeah, I would prefer to avoid those versus adding a bunch of plumbing so that you can mostly pretend they don't exist
anyway, people do use zenject and there's other ones too
I just wouldn't unless you have a very good reason (like you're working on a size of team where extreme decoupling is important)
well you're always welcome to post some code and maybe people will have advice on how to decouple it
it's just that good code mostly comes from meeting the specific needs of a situation, not applying some general pattern globally
so you gotta do what you gotta do, and it's hard to offer real advice without something concrete to work from
I can descrbie the pattern im using; there's no real need for me to post the files (too many of them)
To keep it simple, any class that kinda acts as a root class or a manager class passes a reference of itself to any objects it creates, and then those root classes kinda act like a hub so that all the objects instantiated in them can access stuff from all the other instantiated in them
idk dont worry about it, I think im fine tbh
yeah, sounds backwards to me
most games make more sense when you think top down than bottom up
instead of telling individual objects what to do and having them all reference managers which they then need to delegate that to, you can have your objects be stupider and let the managers manage them directly
I see very little value in the kind of indirection you're describing (though if you do, that's cool) and as you say, it means you have to do some silly dependency management
could you provide a simple example, if possible?
true, I did make that mistake
What does this mean?? Should I be using something else?
not off the top of my head but you can look into ECS style architectures which take that approach to the extreme
What you're doing will create a new array and throw it away every time versus reusing one, which is less performant than it could be. I'd probably swap over since the differences are minimal, but it's unlikely to be a big deal unless you have a lot of whatever that component is.
yeah, I mean it's probably a micro-optimization that won't matter either way but I would prefer to not create the garbage
and the API is slightly different in a way that could be educational, so give it a go
Mmm, do I need to give the NonAlloc a maximum of hits?
Cause it's kinda unclear how many I would need tbh
yep, one of the things about programming with memory in mind is making those kinds of decisions ahead of time
ideally you wouldn't have so many collisions at once that it's a concern
Yeah, but it migth happen that the actual thing I am looking for is behind a bunch of non-related colliders
how about some layer masks
Hay, I am looking to get into Unity. Are there any good resources I should know about for coding?
I have a lot of experience with C++ for microcontroller applications but I have yet to really work with C#.
there are beginner c# courses pinned in this channel and the pathways on the unity !learn site are a good next step
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thankyou very much!
I just sat down and did the basic moving cube.
It's my first time coding anything higher level. I have a lot to learn
Just found the unity 6 documentation. It should help a lot with things.
is there a component that fades a texture into another one?
Having also come from C++, I found C# to be pretty easy to settle into
Yeah it feels very familiar. It feels like I mostly need to learn what unity can do.
Planning out and executing higher level systems is also something I had to get better at. It didn't help that I'm making a simple RPG, and that's systems upon systems upon systems 😄
I am coming off of a very difficult C++ project lol. So this is very fun.
I was working on a electronic board game that uses nfc tags to read what cards you played.
Dealing with learning a real time operating system to run on a esp32
Now you get to make the game part of the game, and not worry about how the hardware interfaces with all of that
Why in my game 4 pieces in wrong place and the other one is out of place with them, I think this is a code issue.
private Dictionary<GameObject, List<int>> piecedictionary = new Dictionary<GameObject, List<int>>();
public GameObject inventorycount;
void Start()
{ // Add pieces to the dictionary with their values (attack, number of pieces, number of rows )
piecedictionary.Add(GameObject.Find("Prince"), new List<int> {675, 1, 1});
piecedictionary.Add(GameObject.Find("Junior pawn"), new List<int> { 75, 12, 6 });
piecedictionary.Add(GameObject.Find("Senior pawn"), new List<int> { 225, 8, 4 });
piecedictionary.Add(GameObject.Find("Knight"), new List<int> { 400, 2, 2 });
piecedictionary.Add(GameObject.Find("General"), new List<int> { 450, 2, 1 });
foreach (GameObject key in piecedictionary.Keys)
{ // Create a TextMeshPro object for each piece in the dictionary
Vector3 offsetvector = new Vector3(-0.08f, -0.32f, 0);
GameObject inventoryspawn = Instantiate(inventorycount, key.transform.position + offsetvector, Quaternion.identity);
}
}```
Yeah not having to minimize the file sizes to the max is nice.
"Did I use C style strings or C++ strings for this?"
type stuff
I had an Idea for a game I would like to make and it will be a fun side thing
Are you expecting them to be in the order of prince, junior pawn, senior pawn, etc?
My end goal for learning unity is a mech game with a unique high skill ceiling movement system.
Yes but my issue is all 5 texts are not aligned, they should be aligned.
Well dictionaries have no order when you foreach over them, they're stored in a way to make accessing by key quick, but this means they can't be iterated over in any expected order.
As for text, you mean the number on the icon?
Yes it is
Are the "Prince" and other items in the UI, or are they in the world? Because if they're UI then you don't want their transform, you want their RectTransform to place them properly
No ui for those text.
So the Pieces are in the world, and the "text" isn't really Text, it's a sprite of some kind?
It looks like the pieces are Images though, from the screenshot of your hierarchy
It will be much easier to place the UI Text on the UI Images exact position with that offset
just read a short article on ECS. Their point was for systems where you really need multiple inherticance, ECS is the better choice. I think multiple inheritance and passing references around complex hierarchies are similar problems, so i get why you recommend it. Is your point that you could define state management classes as like entities/components that can be accessed from anywhere?
Generally the "dumber" your low level monobehaviours are, the better. ECS just goes the extra step of having those components be nothing but data storage with no methods. The state management is handled by systems, which will take care of processing every entity based upon what components they have.
☝️ Yep, though you don't have to go that hard since it only makes sense for some things. You'll find that some code, especially presentation code, feels better with more 'doThis' kind of methods. It's just that they're then controlled by high level systems which can consider all the things they need to know, rather than individual agents who either have no context, or need to be passed all sorts of random context to do anything useful.
I go a quasi-ECS route where I have separate systems classes that listen to events and process specific parts of my game. Helps prevent me from making god classes, when instead I can have a class just for leveling up, and another just for processing damage over time. Nicely compartmentalizes those mechanics.
how do the high level systems have accesses to everything they need
In pure ECS, they have access because the entities and their components do not hide any of their data. Its all public.
In something less extreme, you'd probably go with properties that manage some of it to prevent things getting out of hand.
Really however you want as long as systems have some way to query data. You could even use the unity scene and Find calls at initialization time and that would probably be ok. Depending on the game you're making, I would recommend either:
- The managers are the sources of truth for everything, and so have references to whatever exists within their domain, either because they created it, or it registered itself with them at initialization time.
- Your state is stored in a blob that's globally accessible.
or some combination, I guess
I sort of do both
So like for a movement system, I'd have a movement state calculator system, A gravity calculator system, whatever kind of functionality I need I can have a system for. And then these all have access to the global state of entities as their input?
essentially, though movement is one of those things that tends to end up tightly coupled and I wouldn't fight that
again, everything depends on what you're making
interesting, I doubt im going to make any changes to my movement system rn, but this is def good to know for the future
Just because its really a one time problem system with setting up the framework, which like you said is bound to be a mess for movement, but once its done modifying the system and adding behaviors would be straightforward
Appreciate it lads
so you treat your monobehaviors as low level data inputs, and then send data "up" the hierarchy for processing?
In pure ECS, nothing gets sent up. I haven't done much with it, but generally ECS can quickly iterate over all entities, so systems can see what entities with specific components need to be processed. Something without a bullet component gets ignored by the bullet system, and so on.
For something like what I'm doing, here's a UI example. I used to have AbilityButton which was a fancier Button that knew what Ability was assigned to it. The icon, the text, etc.
Eventually I realized that was unnecessary and tangled up. It was better for the button to just be what it is, it didn't need to know what ability was assigned to it. A layer above it would assign the correct icon and text to it, and add itself as a listener to the button being clicked. Then remove itself as a listener and clear out the button's icon and text when no longer in use, or set the button inactive altogether.
top-down
My monobehaviors are just how I display the gamestate to the user. They contain no game logic or meaningful game state themselves (but I wouldn't build all kinds of games that way)
just got here 😋
so I see the value of an ECS like setup / separation of data and behavior for things like buttons or whatever that have a lot of variation in how they can be setup or a lot of different behavior. For something like a movement system though, the complexity more comes from having a lot of systems needing to interact, not necessarily needing super modular design, so I'm having trouble seeing if it applies.
so is there like a beginner's guide to programming lingo cuz i am confused XD
programming lingo or programming?
lowkey just lingo for the discord cuz there are alot of abbreviations i dont understand
Google. Or ask ai. It's pretty good at explaining/rephrasing common concepts. Just make sure you include the context.
Or ask the person you heard it from. Sometimes people come up with words or abbreviations that don't event exist.
sorry just nervous since im just starting out in here and script altogether
nothing to apolgize for brotha
Well from the little you've said, my suggestion is to manage the complexity you've described through globally readable state and/or keeping your data flowing in one direction (top-down). Everything else is just perspectives on how you might do that.
this is not really a code but I need help.
just one last question; even in ECS, can a system maintain some of its own state? Cause it doesnt really make sense to me how all the state would be separated
The idea is that you wouldn't need to, no. You do often need 'singleton state' of some kind though, which you can put on some kind of special entity for that purpose, or some ECS implementations include 'world state' which is a slightly neater version of that. Also note that this is all something you'd mostly use for gamestate, not UI state, which could live in systems if you wanted
Ok that makes sense
and for communicating between systems, you'd usually add or remove components from an entity, or modify their existing components
i'd assume the goal would be to limit the use of singleton entitys as much as possible? or no
you end up doing some things which feel slightly weird at first, like having a PlayerInputSystem which adds a WantsToMove component with some movement data, which is then processed by your actual MovementSystem to do the movement
the result of this though is that you're forced to keep everything data-driven which ends up being very useful in many cases
whatever works? I don't have a strong opinion
it'd depend on the game
I guess if you feel like you need a lot of those, maybe ECS isn't the best fit for that kind of game
having this horrible issue where my game gradually allocates more memory until I hit memory exceeded and the webgl game just crashes and I dunno how to debug this! any help would be appreciated
It's called a memory leak. You can debug it with the memory profiler.
You'd need to debug it in the editor or a desktop build though
should I be using the package? I tried to debug but like I don't really understand how to glean any info from the default profile
The package would provide more info, yes. But you still should be able to make some conclusions based on the regular profiler.
so I got this thing pulled up now, how can I find any memory leaks or weird behavior?
Is that during play mode?
yea
Select a frame in the graph and it should show more info in the bottom tab.
You can look at what exactly is being allocated.
I haven't used the memory module in the regular profiler in a while, but in the memory profiler package, you can inspect different memory categories in details.
You should probably go and read the manual a bit on how to use it.
should I use the package then?
honestly I am under a lot of time pressure here to figure out something really quick
it's a game jam submission and the deadline is in like 12 hours
unfortunately the crash happens consistently - the game starts off using like 600 MB of memory and gradually increases until it exceeds roughly GB and taps out
You'll need to spend some time learning how to use the necessary tools. There's no going around it. Granted, reading the manual shouldn't take too long. Maybe some 10-20 minutes depending on your experience.
when u say manual, do you mean for the profiling package
That or the regular profiler. Depending on which one you want to use
Use the memory profiler package. Take a snapshot at the start. Wait a bit for memory to increase take another snapshot and compare them in the UI. Profit.
Hey everyone! I've opened Visual Studio for the first time via unity by following a Unity Begginer tutorial I found on YouTube. The guy says that I'm using things in C#, but that's not the language I plan on learning. Do I have to calibrate Visual Studio/Unity in order for it to accept C++ or does it just accept any language I feed it?
if you want to use unity you'll need to use c#
c# is easer
Alright sorry. I myself was thinking of the wrong language, turns our C# is what I'm using. Sorry to bother yall.
just make sure you configure visual studio so you get intellisense 👇 !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Why cant I select all the frames and drag it into the animation timeline like the other animations
this is a code channel. but you need to select the object you are animating, and add the sprite renderer's sprite property
My bad thanks for the help
So Im following that tutorial, and noticed that when this guy types it pops up with what I'll call "suggestions," gut when I do it I dont see that. How does one turn that on?
configure your ide according to the embed boxfriend sent above
also that's visual studio code, not visual studio. blame microsoft for the naming
So am I using the wrong software?
no, it's valid; it's just not the one you said it was
Shuld probably get what the tutorial has, thats probably smart.
Ty.
it's visual studio mac in the video, that doesn't exist anymore (visual studio and visual studio mac are also completely different apps)
So should I look for a diffeent video int hat case seeing as its using something so outdated it literally doesnt exist?
there are 3 main options, vscode, vs (windows only), rider. (in no particular order)
do you have experience with any of them (or any jetbrains products)
no, ide choice doesn't really matter in the grand scheme of things
it's just a tool to write code
there are plenty of tools that do approximately the same thing with small differences in usage
I didnt even lknow Visual Studio existed until looking up this video, so no I dont have any experience
Can someone please explain to me why this jitter is happening?
Probably collider related?
Dunno why im responding like i could possibly know
ok, so imo just pick one and stick to it
your choice isn't final, but like i mentioned before, the 3 choices differ slightly, so if you get comfortable with one it'll be easier to work on that particular ide
when searching for tutorials should I be searching my specific software?
how are you moving the character? physics, animation, or what?
no, the differences don't matter for actually making stuff
movement.x = input * speed * Time.deltaTime;
transform.Translate(movement);```
you'd only need to search for your ide with stuff related to the act of writing code, like "find and replace" "find in project" "rename symbol" "find references" etc
and how are you doing collision?
Im just using this built in stuff no code
a static rigidbody? is this on the terrain or on the player?
Terrain
hm I've found that it's not a memory leak in the traditional sense but rather at specific point unity repeatedly tries to allocate memory until it goes up to 20+ GB on my editor before I kill the process lol
This is the player
ok so you're using a rigidbody; that controls the transform. you shouldn't modify the transform directly, since it would conflict with the rigidbody's control, leading to unexpected results like you're seeing.
you have a rigidbody already, just use that for movement. the equivalent rigidbody control to the motion you have now would be setting the rigidbody's velocity.
it would be something like this (spoilered in case you want to figure it out yourself)
||```cs
Vector2 vel = rigidbody.velocity;
vel.x = input * speed;
rigidbody.velocity = vel;
btw @maiden estuary this message was for you, in case you missed it
Thank you very much for the help :)
why is it different
which editor you have ?
if its not in the dropdown you missed a step
yeah im running through the setup for Unity I think I just sety it up wrong
you installed VS through hub?
i dont even remember shits been on my pc for almost 2 years
so I just redownloaded it and am re-setting it up
then you should probably make sure you have the unity workload first
well i got the thing for unity from the checkboxes, so thats a start
Im usint the guide in the bot
checkboxes?
did you restart unity after you installed unity workload
I should restart unity yeah
What have I done wrong here? It wont let me enter play mode, and I'm not seeing any indicator, if there is one, as to what I've done wrong.
The class scope is not closed.
the what
Class
Scope
Do you know what the curly braces are for?
Guys Im watching says theyre like fences that make sure that this code is only executed once th egate has been opened
which is the code that I am currently trying to execute
related image
This explanation doesn't make sense.
The curly braces define the scope of class/structs/methods and other code structures. They define what belongs where.
And they always come in pair. If there is an opening brace, there must be a closing one
But mine are closed are they not?
Count the open and close ones and see for yourself
Theres 2 {, and 2 }
No
Or am I just dumb
what
huh?
What the fuck am I
Im sorry its like 4am I am rather
tired and I am very confused
So, does that fix your issue?
Makes sense?
there's an indicator right here
might be a bit hard to see, so check the console/problems tab as well
where the hell is that
on the last line
No the problems tab mb
so wait aminute, how is this not closing it?
is this supposed to be in reverse?
Did you have a look at my screenshot?
First of all, you can hover over the code underlined with red to get a popup. And then you can also open/dock the errors tab if it's by default
So wait a minute
it's not closing the class, it's closing the method
{ leaves it open, correct?
you didn't have anything closing the class
how do I accomp[lish that?
Ive made bar for bar what this guide is telling me
have I not?
}
[SerializeField] private GameObject slot;
private GameObject[] slots;
// Start is called before the first frame update
void Start()
{ // Add pieces to the dictionary with their values (attack, number of pieces, number of rows )
piecedictionary.Add(GameObject.Find("Prince"), new List<int> {675, 1, 1});
piecedictionary.Add(GameObject.Find("Junior pawn"), new List<int> { 75, 12, 6 });
piecedictionary.Add(GameObject.Find("Senior pawn"), new List<int> { 225, 8, 4 });
piecedictionary.Add(GameObject.Find("Knight"), new List<int> { 400, 2, 2 });
piecedictionary.Add(GameObject.Find("General"), new List<int> { 450, 2, 1 });
slots = new GameObject[slot.transform.childCount];
for (int i = 0; i < slots.Length; i++)
{
slots[i] = slot.transform.GetChild(i).gameObject;
}
foreach (GameObject key in piecedictionary.Keys)
{
int dictionaryindex = piecedictionary.Keys.ToList().IndexOf(key); // Get the index of the key in the dictionary
// Create a TextMeshPro object for each piece in the dictionary
Vector3 offsetvector = new Vector3(-0.08f, -0.32f, 0);
GameObject inventoryspawn = Instantiate(inventorycount, slots[dictionaryindex].transform.position + offsetvector, Quaternion.identity);
}
}``` There is an error called index was outside the bounds of the array, how to make the index in the bounds of the array or the array outside the piece index.
you have not
Probably not.
Start with reading the whole error details and the line of code that throws it.
So then what have I done wrong? How is Image One different from Image Two?
they aren't different
Then why does his work and mine doesnt?
but there are other differences in the file
buddy slow down
every { needs a corresponding }
you've successfully done that for Update
The image on the left only shows part of the code. Specifically the method definition. It doesn't show anything about the class that it's in.
you have not successfully done that for the entire BirdScript class
there's a { right here. where's its corresponding }?
the error should be telling you, "} expected"
or i guess "unexpected EOF", not sure
the error: ``` GameObject inventoryspawn = Instantiate(inventorycount, slots[dictionaryindex].transform.position...);
I have added this and the program is noticable more angry at me than it was before
how so
Ok, so it is likely on the slots[...] line. The error means that the array length is <= the index that you pass in.
why do you have dictionaryindex anyways
dictionaries don't have indices
yeah you put it in the wrong spot lol
Because this is not where you add it.
oh my fucking god I see it
You should probably start with the basics !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
you're saying the class is empty, and then you have a bunch of random code after it
} needs to go at the end, meaning the other parts are inside the class
there we fucken go
As soon as I noticed theres not a } at the bottom i instantly got it
The way the tutorial cut fucked me ut
are you ever going to do like, piecedictionary[piece]? if not, you should probably just use a list of structs where the structs have the gameobject and the list of ints
ty and I apologize for my density
even if you are, you should not have that dictionaryindex thing
instead, extract the keys list out into a separate variable, and then loop over that with a c-style for loop
Im currently watchign a tutorial for a begginer
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and...
This doesn't really teach you proper C# basics, so you should look up something on that separately.
I plan on using CS-50 for it, I just thought learning the actual engine itself would be better off at first
I mean it just seems logical to understand how to use the paper before using the pencil
how can I make a good jump like when he jump he continue at his speed but when he go to opposite direction it move slowly.
Someone here trying to learn how to script in unity?
I do want to learn together with someone who does want to and do some projects together 🙂
DM if you want..
we don't condone DM support here. it defeats the purpose of having a community server.
also, see below
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
if you're looking to learn, check out unity !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
oi Chris lead me a hand @naive pawn
don't ping specific people for help, just bump your question
no just you always help me soo........
you know crash bandicoot right?
when he jump, in the air he continue at his speed to the direction but when he goes opposite direction it goes slow down( it's hard for him to getcontroll on mid air)
and sorry for ping.
yeah
the answer is kinda just re-arranging the sentence 😄
reduce the control while in air
english 50 50.
😅
fair, I mean more about pointing out how to think about the problem logically than specifically language though
breaking down what you want into the separate steps
3d unity
void Update()
{
ForBack = Input.GetAxis("Vertical");
LeftRight = Input.GetAxis("Horizontal");
Vector3 move = new Vector3(LeftRight, 0f , ForBack)* speed;
Vector3 newVelocity = new Vector3(move.x, rb.linearVelocity.y, move.z);
rb.linearVelocity = newVelocity;
if(Input.GetButtonDown("Jump") && IsGrounded()){
rb.AddForce(Vector3.up * JumpForce, ForceMode.Impulse);
}
}
bool IsGrounded(){
return Physics.Raycast(transform.position, Vector3.down, 1.1f);
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
🫱🏿🫲🏻
so im trying to run a collision for a bunker, replicating space invaders. and for some reason this code will only detect the missiles and not the invader. i have the exact same code for the player, and it works for the player, idk if its the collisions. anything i should be looking for? ive got it on the right collision layer, but am stumped?
make sure the collision in question matches the matrix
https://unity.huh.how/physics-messages/trigger-matrix-2d
oh ur a life saver. needed a rigidbody on my invaders. thank you, thats a nice little chart
hello again im starting to learn C# language so i can understand script a little better using some lesson thingy called brilliant honestly its pretty fun to use
Is there a way to execute OnEnable in both play and edit mode but not affect other functions?
If I add [ExecuteAlways] on the class, all the methods will execute in editor, which is not what I want.
you could check for Application.isPlaying in other functions, i guess? i don't know of any other way
yeah, but that requires editing all the other functions, thanks either way
I would've just used a ContextMenu item if you don't want stuff getting run in editor
Not fully, anyway
why the icon within my invetory bar is pressed like this.
Avoid nonuniform scaling to resize things. Use the rect tool [T] or width and height properties to resize UI elements.
can u isolate that function or features to a script?
thought of that too, not a really good solution
it's fine either way, I made all the functions work properly with ExecuteAlways now so ye
execute always or in edit mode will affect all functions inside the class , its either 0 or 100 , no 50.
if u only have a particular function thats not needed for execute always, u need to isolate it out
or go find another attribute tag that can ignore execute always
can someone give me a rigidbody addforce based movement script or tutorial which doesnt use drag to slow the player down? after drag gave me a lot of issues i switch to setting velocity instead of addforce. this is also giving me problems now, so i would like to swtich back again
Can I tell a script to do something when its game object is destroyed directly or do I need an event for that?
my buttons dont work, trying to run a function for a main menu button and for some reason they wont let me click them.
There is probaly something on top of them
this is how i have it, is it bottom to top or top to bottom, in order of placement
If the background it's a big panel it may be totally covering the play button
OnDisable?
On dissable it's not just when it's turned off?
does the canvas have a graphic raycaster
lower in the hierarchy means it draws on top
it is turned off in the process of destroying the gameobject
yes
thanks
but still not allowing to click
ive deleted the background and now just have buttons, but they still dont work, could it do with the function itself
like this is how i have my quit and it wont work, am i missing something
Are u even making sure that is being called?
you need to
- Put a graphic raycaster on each canvas component that the button is part of, not just the root.
- Check that the component can intercept/block raycasts (the graphic image component next to the button or below it must "block raycasts" and exists, and is not part of a canvas group that is set as "non-ineractive")
- Ensure there is a EventSystem in the scene and it is configured correctly
- Make sure the button is under a canvas.
- Ensure the button is not part of a CanvasGroup that is "non-interactive"
i believe so
Yeah, but that comes by deafault
doesn't hurt to check
assume nothing in #💻┃code-beginner
Also ensure there is a EventSystem in the scene and it is configured correctly
Are you testing this in a build or in the editor? Application.Quit doesn't do anything in the editor
I meant a debug or print on the method....
so im not sure i understand all of that fully but i havent changed anything from the defualt and this is how my raycaster is
ye ive got a deug set up on the play button and not getting anything through
did you check all the things
I will restart it, as it only takes a couple sec, and if it still doesnt work ill come back, thank you otherwise
is there any guide on making a book in game then viewing its content on the screen? i do not know what they call it
any help please
no, people will not give you a script, no one will do your work for free. Likely no tutorial out there will fully cover the exact movement you want to achieve in your game. If you need help with code, then ask properly. Saying that you have problems is too vague for anyone to help
Yeah, the idea is I am attaching an object to another gameObject with transfrom.parent I want that when the parent is destroyed the attached object drops where it is instead of being destroyed alongside it
there are definitely tutorials out there on google if you search for it. It really depends what you want this to function like but I assume the coding part of this wouldnt be complex at all since you'd really just be choosing which string to use at a given time.
"create a book unity tutorial" plus 2d or 3d should get you enough results on google
this is my movement script. how do i limit movement in air? i dont want so just reduce the velocity.. i want to make the force that will be added lesser than when im grounded
How come I'm not able to pass position as an argument?
https://puu.sh/Ksu7g/484f073631.png
i see thank you so far i was only able to make a detection system that tells if the player is near an interactable object (book) but the other part im still clueles on how to make it
You are missing an argument for this function overload
keep track of what the current velocity should be rather than just using moveVector directly in rb.linearVelocity. Your current velocity could MoveTowards the moveVector. Then you assign that to rb.linearVelocity
Quaternion.Identity for no rotation
Check all overloads on the doc page https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Object.Instantiate.html
Oh. I figured since Instantiate(objectPrefab, transform); worked fine, I'd just need the Vector3. I'm assuming transform contains the rotation, then
No that's to specify the parent
Read the doc page
ohh. how exactly can i do that?
i just use two vectors and combine them at the end
finalVector =
(groundVector * finalSpeed) +
(airVector * playerSettings.airSpeed) +
(Vector3.up * gravitySim);```
I have some weird problem where I use
Destroy(gameObject, 5f);
```Now if the 5s aren't up when I exit the play mode, the object is apparently saved in the scene. Is there a reason for that? context might be important, it's instantiated as child of a dontDestroyOnLoad object
it really depends on how you want it to actually open or show the text. I assume the harder part would be making a book with pages visually flipping. Setting the text on each page is the simple part, just having either an array of strings or a bunch of textmeshpro objects that you selectively enable/disable
what part are you confused about? it was quite descriptive in what to do. if you want to keep track of what the current velocity should be, that means storing it in a vector3
oh book page shaders 🙂
https://assetstore.unity.com/packages/tools/animation/book-page-curl-55588?srsltid=AfmBOorAYjaYT3Gh8fKPw-vhOOBjckY2yQE47JBTUrRdY2dMQel3HTph
shaders?!
well i imagine its something like that
wow i need to learn what shaders actually do 
make things pretty
Were there any errors?
dang does this really work? so you just use finalVector to set the velocities?
how can i make my currect velocity MoveTowards the moveVector?
then i have some code in update detecting if we're grounded or not.. if we are groundvector will have a value but airVector will be zero
and vice-versa
groundVector + 0 = groundVector
0 + airVector = airVector
yes, these 3
its a built in function which is why i wrote it like that https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.MoveTowards.html
ohh yea u had a null error.. probably paused ur code execution
Create a bool to be evaluated if the player is in the air. Modify move vector x accordingly relative to air state.
I assume it is somehow instantiated in the editor then, because it doesn't resemble the altered object but rather the normal prefab
well can u show the instantiation code?
ill make a pastebin
thanks! i will try this
Is the instance creating code on a scriptable object (an object that will persist when the application/play-session closes/terminates)
how do i modify move vector? like what should i modify move vector as?
either moveVector = input * groundSpeed;
https://pastebin.com/SeyZ4upF hope this link works
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
or moveVector = input * airSpeed;
then u can use a simple if statement to assign whichever version u need
ohhhh okay.. thanks a lot!! i will make sure to try that
if(inTheAir)
moveVector.x *= lesser;
...```
1st is how it looks after game start because it saved due to the problem, 2nd is how it looks when instantiated in scene
https://pastes.dev/Dhn86CuRFy heres my CC script if u want to look n see
my Lerps are awful.. so ignore those.. i'll change em to smoothdamp or movetowards eventualy
thanks a lot! i will give this a try too
omg thanks a lot brother!
Move() and PlayerInput() are the two important functions in ur case
should not be, it's just a singleton with ddol
thats the confusing part..
why would something u add during runtime be left over after u stop the game?
exactly
have u tested it out on some other part of ur project?
Destroy may not be called from edit mode! Use DestroyImmediate instead.
this line in the error implies that it's trying to destroy in edit mode
maybe its just this specific situtation causing an issue like that
ur calling it from Runtime tho right?
yes
DestroyImmediate is for things like Editor scripts
but maybe due to the 5s delay?
in the pastebin yes
not the singleton part, but other than that yeah
i can look.. thats all i can promise
thanks :)
Can you show the inspector for toast?
Destroy(gameObject, 5f) schedules a delayed destruction at runtime, only if the game keeps running.
If you exit Play Mode before the 5 seconds pass, the object never gets destroyed, because Unity stops all coroutines, tweens, and delayed calls immediately when exiting Play Mode.
BUT since the object was instantiated inside a DontDestroyOnLoad object, Unity moves it to the special "DontDestroyOnLoad Scene."
Unity can't clean up stuff that's been manually moved to that internal scene unless you do it yourself — so it persists even after you exit Play Mode.
Short version:
Destroy() was scheduled but never happened because exiting Play Mode interrupts the process.
Anything in DontDestroyOnLoad outlives normal cleanup unless manually handled.
does this seem legit ^?
i think I got something
void OnApplicationQuit()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
foreach (Transform child in toastParent)
DestroyImmediate(child.gameObject);
}
#endif
}```
clear toasts manually at exit
I apparently called the method somewhere in an OnApplicationQuit()
The scene should default though after exiting the play session 🤔
you most definitely dont need to delete objects manually like that
right right
i was going to suggest that maybe you were calling it from some editor function. interesting this causes it as well
^ ya i thought that at first too but
Sorry for all the fuss, that was it probably 😅
lol (╯°□°)╯︵ ┻━┻
i wonder if my toast system still works
just as a note for the future, none of the code you shared used unity functions. meaning none of this wouldve ran by itself, so something else was calling it. it's usually worth going through and showing all the places that call it. You can usually right click the method in your IDE and find all references
im guessing this was AI also?
it was my phones gemini..
absolutely, i just assumed the flaw was in the destruction part :'(
just curious how gemini handled reading over it
something something community conduct ai bad
if my projects would open THIS century
can i possibly see ur generic singleton code?
I got this online and changed some small things.
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static readonly object _instanceLock = new object();
protected static bool _quitting = false;
public static T Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null && !_quitting)
{
_instance = FindFirstObjectByType<T>();
}
return _instance;
}
}
}
[Header("Singleton")]
[SerializeField] protected bool dontDestroyOnLoad = false;
protected virtual void Awake()
{
if (_instance == null) _instance = gameObject.GetComponent<T>();
else if (_instance.GetInstanceID() != GetInstanceID())
{
Destroy(gameObject);
throw new System.Exception(string.Format("Instance of {0} already exists, removing {1}", GetType().FullName, ToString()));
}
if (dontDestroyOnLoad) DontDestroyOnLoad(gameObject);
}
protected virtual void OnApplicationQuit()
{
_quitting = true;
}
}
i also grabbed my online.. i just wanted to compare
thank you friend! 🙂
you're welcome! Might you also show yours? ^^
sure!
i took mine from Vertxyz
huh.how.xyz? vertx.huh.how.xyz something another
can u help me with an asset ?
not unless u go into a bit more specifics
do you know about base.Awake()? It seems you could also use that. Idk if your DoAwake() is by preference
and then its hit or miss
thats vertxs preference
ive been trying to get used to it
but sometimes ill still accidently use the wrong type of awake
A coding asset?
could use a template like me so the singleton is created with the method
howso?
Pretty sure it was placed there to expose insertion of code to the awake method
using UnityEngine;
namespace SPWN
{
public class Widget : Singleton<Widget>
{
public Texture2D widgetTex;
protected override void DoAwake() { }
}
}```
heres how i typically make my singletons ^
nop a map creator
overrides/protected/virtual/ etc still has me a bit confused from time to time
let me make another pastebin
since DoAwake() gets called by the Singletons Awake() method..
And Awake isn't polymorphic in vertz sample to ensure the base behavior always occurs with or without users explicitly calling a base awake
using this you can create them via right click -> creat -> Code -> Singleton
Ohhh u just mean making a MenuItem
make sure to put the scripts into the Editor folder too
makes it a lot easier for me
yea.. i know..
i try to stay away from editor scripting
i tend to fall hard down a rabbit hole
but- but... automation... :(
yea i know
double edged sword for me for sure
is there so much cool stuff to do with that?
i.e.?
i wish i could just create a "Build Game" button
I tend to do the same thing but in my IDE since that feels like a more reasonable place to create scripts from to me
no editor scripting that way!
i get lost for days
tbh mostly I just copy a file that I already have that's in the right structure and update it >_>
hi guys i need some help in unity AR mobile app , with the default XR template .. i want to create an app to view my model and rotate and scale basically
#🤯┃augmented-reality and you'll need to provide more information than that
pretty neat, feels a little over the top for me xD
ok
thats my entire point
can I import a package from git url dynamically via editor scripting?
Using DoAwake ensures the derived class' initialization occurs after the base Singleton. This is better because it prevents user error from placing one (their code) before the other (base code) . . .
yeah i can see that, that's what I meant with preference
Project Directory Markdown Generator 😉
ya, all the time
soo much faster to read my project dirctory from a text file
than to spend 30 minutes uncollapsing things and searching around
understandable
what if...search?
and if im totally honest.. lots of this stufff was made b/c i wanted to..
and then i fell into that rabbit hole. and made things i really didnt need
i just need to stay really alert and focused when working on editor scripting
sometimes i dont know what im lookin for 🫠
its mainly for thirdparty cleaning... (and using it for Asset projects, so i can keep my Directory clean and organized)
after about a month or so of importing and exporting i'll go in and check the project directory out and get rid of residual stuff
I feel the same way. I'm trying to look for scripts where I can change the layout because I want to learn editor scripting. But, it's a LOT of boilerplate (so verbose) . . .
Unity has some pretty nice windows default
u just gotta find em
my first forte into Editor scripting was with the URP Template Readme thing
Oh yeah, I copied a few things they did for myself. I ended up making an extension class for all the styles, add/remove uss classes, binding properties, and setting text because that's a lot of repeating code . . .
I bet anyone who messes with editor scripting has their own . . .
not yet.. but im getting there
i have a WindowData class that I can create
and use that to style my windows
has text sizes, window sizes, scroll or no scroll, icons/ and header graphics, etc
then i can just create my editor window and pass in the WindowData i want for that window
Features acts as
Headers
and anything beneath it will be
- bulleted
still figuring things out.. but today is Not an editor scripting day
Whoa, I like that. That's dope af . . .
thanks!
one day ill get around to implementing it 😉
I have notice the scroll component does not detect when you are moving the mouse and click as a drag, but rather you need to stay still with the mouse for a moment and then drag. Is there some way of overriding that?
Usually you can dissect it a bit and change it up. I do it for buttons sometimes and throw on my own IPointer events
What event am I looking for?
Heyhey people! I was here f or a s imilar issue before and I thought I fixed it but its definitely not fixed.
It's really weird, everything in my game changes its speed depending on the framerate, the jumping, the speed of fish (its a fishing game), but not running speed.
Ive tried using a variety of Time.deltaTime, Time.FixedDeltaTime, neither work, and for some reason when I tab out o f the game while im in it everything gets very very slow and I can only fix it by restarting my game.
Any suggestions?
no suggestions.
we haven't seen the code
It's kinda hard to show the code- in my code, I use Time.Delta time in like 6 different scripts, being movement, camera, fish, shop, movefish, I don't know if I should send all of that
I can send the movement though, which is probably the biggest problem
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO.Compression;
public class movefish : MonoBehaviour
{
float Animation;
public GameObject Fish;
private float x;
private float y;
private float z;
private float iy;
private float iz;
public float num;
public float randint;
public bool Copy;
public float value;
public float enemyinc;
void Start()
{
iz = Fish.transform.position.z;
enemyinc = 3;
}
void Update()
{
if(!Copy)
{
if(Fish.transform.position.x >= 35)
{
Destroy(Fish);
}
if(Fish.GetComponent<Fish>().isAlive == true)
{
num += Time.fixedDeltaTime/4;
y = iy + (2f * Mathf.Cos(num * 2f));
Fish.transform.position = new Vector3(Fish.transform.position.x + 0.02f, y + 0.5f, Fish.transform.position.z);
} else {
Fish.transform.position = new Vector3(Fish.transform.position.x + 0.005f, 0.73f, Fish.transform.position.z);
Fish.transform.rotation = new Quaternion(90f, Fish.transform.rotation.y, Fish.transform.rotation.z, 0f);
Fish.GetComponent<Outline>().OutlineColor = Color.white;
}
} else {
enemyinc -= Time.fixedDeltaTime/4;
num += Time.fixedDeltaTime;
z = iz + (2f * Mathf.Sin( 10*num * 0.2f));
Fish.transform.position = new Vector3(Fish.transform.position.x, Fish.transform.position.y, z);
if(enemyinc <= 0)
{
enemyinc = UnityEngine.Random.Range(4.0f, 8.0f);
GameObject NewFish = GameObject.Instantiate(Fish);
NewFish.GetComponent<movefish>().Copy = false;
NewFish.transform.position = gameObject.transform.position;
randint = Mathf.Round(UnityEngine.Random.Range(0.8f, 2f) * 100.0f) * 0.01f;
NewFish.transform.localScale *= randint;
NewFish.GetComponent<movefish>().value = randint;
}
}
}
}
why are you using Time.fixedDeltaTime though
i was using Time.deltaTime and it wasn't working, so i was t rying fixedDeltaTime
Time.deltaTime should work fine, if it wasn't then you used it wrong. Replacing it with something else related to physics instead isn't exactly a way to fix that lol
as i said in my post, it was "working" but everything moved depending on framerate, so thats why i decided to s witch to fixeddeltatime
but both still have the same problem of being dependent on framerate
do you know the difference between time.deltaTime and fixedDeltaTime ?
i think so
that means you used it wrong then because Time.deltaTime was literally meant for this usecase
probably placed it at the wrong spot, or its something else
i used it the same way im using fixeddelta time
just with different proportions obviously
i dont see how thats using it wrong
I'm trying to see where, cause this code is a mess
sorry
Can you post the scripts in a paste site, easier to search for specific stuff that way
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also are these rigidbodies in any way?
fixedDeltaTime is the tick speed (1/tickrate) of the physics system
deltaTime is the frame speed (1/framerate) of the update loop
literally the difference (delta) in time between the last iteration
if you do, say, value += deltaTime in Update, then after 1 second, value will be incremented by 1.
same for value += fixedDeltaTime in FixedUpdate.
but fixedDeltaTime is unrelated to Update, so it doesn't make sense to use it there
This depends on framerate, for example sc Fish.transform.position = new Vector3(Fish.transform.position.x + 0.02f, y + 0.5f, Fish.transform.position.z);
You are adding 0.02 and 0.5 to the position regardless of the frame duration
A tool for sharing your source code with the world!
anything that changes over time in Update, FixedUpdate, a coroutine, probably other stuff, all rely on the loop rate. for Update and coroutines (except WaitForFixedUpdate), that's the framerate
Also please use proper names for variables, num or enemyinc don't tell me much
yaa variable names here making 10 times harder to read than it needs to
im sorry idk what to say its just how i code
This part is also wrongcs Fish.transform.rotation = new Quaternion(90f, Fish.transform.rotation.y, Fish.transform.rotation.z, 0f);
Quaternion values aren't euler angles - you probably want = Quaternion.Euler(...)
And instead of rotation.y/z you'd use eulerAngles.y/z
never to late to get into better habits 🙂
don't take it as criticism on you.. we all been there.. its good to improve for your future self
how is it wrong?
its working so i dont see a problem with it
oh okays C:
quaternion values dont go above 1
you should never manually create quaternion values that way
always use helper function with euler angles
Quaternion.Euler, rotation.EulerAngles etc.
but in regard to this, how do i change this so its not frame dependent?
Multiply the value with Time.deltaTime so it scales with the framerate
With that you also need to use larger numbers
Fish.transform.position.x + (0.02f * Time.deltaTime), like this?
you cant directly modify that property like this you get an error
how would i rewrite this?
like this?
Quaternion.Euler(90f, Fish.transform.rotation.y, Fish.transform.rotation.z, 0f);
Same with these lines cs y = iy + (2f * Mathf.Cos(num * 2f)); cs z = iz + (2f * Mathf.Sin( 10*num * 0.2f));
You are adding constant values, the additions need to be multiplied by delta time instead
check docs on the mentioned methods maybe
Yeah, but now the final value is lower so you need to use a larger number instead of 0.02
no you're passing Quaterions into a Euler angle
Fish.transform.rotation is still a Quaternion
so .y gives you a quaternion value
if you want the euler angle of it it would be rotation.eulerAngles.y or transform.eulerAngles.y
alright, so i would do that to uh, everything p much? is there an easy w ay to do that or, just have Time.deltaTime splattered around my code
any time you're adding values over a series of frames / time you need Time.deltaTime
(this is what keeps the adding values consistent through different fps)
It doesn't get much easier than adding one multiplication
alright, was just asking cause i have alot of spots that happens in
Ofc you can add a local variable float delta = Time.deltaTime and use that to make it a bit more readable
that would help
Fish.transform.eulerAngles = new Vector3(90f, Fish.transform.rotation.y, Fish.transform.rotation.z);
like this?
for this, would i just be able to multiply "Y" & "Z" by delta to fix it? or would i have to do it specifically to the values inside?
noo lol transform.rotation.y, is still a quaternion
i meant more like .rotation = Quaternion.Euler(90f, Fish.transform.eulerAngles.y, Fish.transform.eulerAngles.z);
but I would be hesitant using its own eulerAngles into assigning into rotation
The values you add to it should be multiplied. So instead of something like z = iz + 123 you would do z = iz + 123 * delta
Fish.transform.rotation = Quaternion.Euler(90f, Fish.transform.eulerAngles.y, Fish.transform.eulerAngles.z); so like this?
You can probably just do transform.Rotate(myEuler)
Actually nevermind that part, these lines don't need delta time
Just realized you are adding the sine to the initial positions
okayyyy
but yeah technically the code is now correct, if its what you want it to do is another story lol
oh, so it might not turn 90 deg now?
oh no it does, its just sometimes I get adamant passing its own angles sometimes lol
(obv i need to change the values) but, does this look more accurate?
{
num += delta;
y = iy + (2f * Mathf.Cos(num * 2f));
Fish.transform.position = new Vector3(Fish.transform.position.x + (0.02f * delta), y + (0.5f * delta), Fish.transform.position.z);
} else {
Fish.transform.position = new Vector3(Fish.transform.position.x + (0.005f * delta), 0.73f, Fish.transform.position.z);
Fish.transform.rotation = Quaternion.Euler(90f, Fish.transform.eulerAngles.y, Fish.transform.eulerAngles.z);
Fish.GetComponent<Outline>().OutlineColor = Color.white;
}```
at least .rotation = Quaternion.Euler tries to avoid gimbal lock that occurs if you were to assign euler angles manually
https://paste.mod.gg/avbiodunbsaw/0 easier to read
A tool for sharing your source code with the world!
Looks better yeah
okay!!
(im a big dum dum and dont understand half of these words)
gonna be real i dont know what euler, quaternion, or gimbal really is i just use them lmao
Gimbal lock is the loss of one degree of freedom in a multi-dimensional mechanism at certain alignments of the axes. In a three-dimensional three-gimbal mechanism, gimbal lock occurs when the axes of two of the gimbals are driven into a parallel configuration, "locking" the system into rotation in a degenerate two-dimensional space.
The term can...
(I would probably make a local variable for Fish.transform to make it a bit more readable)
quaternion is like another word for r otation right ?
It's a data type containing a rotation
its a 4Dimensional Value
so what like uh float new Vector3 = Fish.transform
its good way to store rotations mainly to avoid gimbal lock + other reasons big brains know about lol
transform is a Transform..
Vector3 myPosition = Fish.transform.position;
Transform myFish = Fish.transform
Quaternion myRotation = Fish.transform.rotation;
https://en.wikipedia.org/wiki/Quaternion
https://en.wikipedia.org/wiki/Euler_angles
https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
if u feel like melting ur brain today
the great thing about quaternions is you dont have to know HOW they work, just what they're for
does this look better https://paste.mod.gg/rbdkccbdtqwj/0
A tool for sharing your source code with the world!
a bit odd naming tbh
Vector3 FISH = Fish.transform.position;
Would be fishPos the fish would be fish.transform
Yeah that's why I'm kinda stepping back, too many instructions can be overwhelming
it was earlier but im good now
i just wiki'd and now i'll spectate 🙂
i did it cause its funny
idk l mao
until u ur scrolling to the top every minute or so checking what the difference between Fish, FISH, and Phish are
ykw fair
You think bad naming is funny until you come back to a code base a couple of weeks later and have no idea wtf is going on
Phish 👅 🔲 👀 🌈
okay i changed it to FishPos
Local scope variables should be fishPos
🐫
yeah very descriptive names can become funny too..
DeleteAllChildren() **enters watchlist **
ykw while im here
when Im searching up how to make bombs and explosives in Google..
stuff gives me warnings sometimes (NOT ERRORS) about something
include the VERY important: "In Unity" to stay off the watchlist
if(Player.GetComponent<Inventory>().Spear.active == true)
unity doesent like when i use this
why?
what does it say
ah yes, use activeSelf
literally .setactive
whats the difference?
its the same thing, but this one is newer
probably some extra stuff done internally I have no clue about lol
ah okay
not sure the difference
tysm guys C: i feel smarter now
when you see ⚠️ its just a warning, not gamebreaking / still compiles fine and works but should be addressed at some point
🗨️ w/e
⚠️ w/e
🛑 hold up..
lmao ye
okay.. i guess from what i understand
this one must have all the parents active as well
no matter how i change the values the fish just arent moving now
shoulda took it a step at a time 😅
yeeeaaaahhh
Show the current code?
A tool for sharing your source code with the world!
You need to assign FishPos back to the fish.transform.position
CleanUpOrphans()
if(transform.parent == null) IAmBatman()
i very well may use this as a function 😄
wait am i dumb
did i not do thata l ine 2?
That just creates a new local copy of the position
Changing it doesn't affect the transform.position, you need to assign it back
value types are copied, you never change the original
So do fish.transform.positoin = FishPos when you are done
ur setting ur own variable FishPos to the Fish.transform.position; but u never do anything with it besides ~~read ~~ set it over and over
set it over and over*
The local variable was supposed to be for the fish transform
But this will work fine
Just extra confusion
heck ya 😄
i was just pointing out that Vector3 would come from a position
not a transform
well, not the Transform by itself.. but its .position
https://paste.mod.gg/bubjpyuwsvah/0
like this?
A tool for sharing your source code with the world!
I have a feeling that y + (20f * delta) is incorrect tho
You reset y to iy + sine every frame so adding a delta scaled value to it doesn't make sense. You haven't told us what it's supposed to do
i see u setting the rotation.. but never the position
Fish.transform.position = FishPos; seems to be missing somewhere.. (if ur trying to move the fish)
okay im getting really confused
i set it in the new code i sent
and yeah its still not working
oh mb i see now
was clicking the wrong link
heres the whole thing if interested
A tool for sharing your source code with the world!
i'd check if ur else statement is ever running then
btw when you add Time.deltaTime you might have to crank up some values

yeee i did
i multiplied them all by like 20
and then i checked and they arent moving at all
i figured it out
i was being stupid
what was it ?
Vector3 FishPos = Fish.transform.position;
if(!Copy)
{
if(FishPos.x >= 35)
{
Destroy(Fish);
}
if(Fish.GetComponent<Fish>().isAlive == true)
{
num += delta;
y = iy + (2f * Mathf.Cos(num * 2f));
Fish.transform.position = new Vector3(FishPos.x + (4 * delta), y + 0.5f, FishPos.z);
} else {
Fish.transform.position = new Vector3(FishPos.x + (0.02f * delta), 0.73f, FishPos.z);
Fish.transform.rotation = Quaternion.Euler(90f, Fish.transform.eulerAngles.y, Fish.transform.eulerAngles.z);
Fish.GetComponent<Outline>().OutlineColor = Color.white;
}```
i needed to change FishPos to Fish.transform.position when setting the new vector
Doing cs FishPos = ... Fish.transform.position = FishPos;Isn't different from doing cs Fish.transform.position = ...
wdym
this is the same thing as this you had
FishPos = new Vector3(FishPos.x + (0.8f * delta), y + (20f * delta), FishPos.z);
Fish.transform.position = FishPos;```
Maybe you just forgot to save before 🤷♂️
Ass jump? Hell yeah
A tool for sharing your source code with the world!
and then this is how i use y
Vector3 movement = (horizontal + (transform.up * y));
controller.Move(movement * Time.deltaTime);```
Idk what you are doing with the fall value but that code also depends on frame rate
yeeee now i need to put delta in there
Maybe just look at a tutorial for character controller jumping and gravity
Because that paste looks pretty bad indeed
okaaayyy
its so that the y value decreases exponentionally
here is how unity does gravity + jump
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/CharacterController.Move.html
they finally fixed it to 1 Move call 🥹
Vector3 finalMove = (move * playerSpeed) + (playerVelocity.y * Vector3.up);
controller.Move(finalMove * Time.deltaTime);
what a time
hello guys, could anyone help me because i dont know why but my particles stopped showing up
#✨┃vfx-and-particles is a better place to ask
thank you
I am destroying a UI element and I am marking the layout for a rebuild but it just doesn't do it. It does get fixed when I change resolution tho.
What am I doing wrong?
I can't import any sound, anyone know what is wrong with it?
Quick question!
Im trying to use logic on this piece of code but I think im forgetting something
What I want to achieve is an object that follows the player with varying speed based on the distance but stops before reaching the player.
Heres the code
Vector2 endPoint = transform.position + (player.transform.position - transform.position).normalized * (Vector2.Distance(player.transform.position, transform.position) - 2);
rb.linearVelocity = Vector2.MoveTowards(transform.position, endPoint, speed * 100 * Time.deltaTime);
What I "THINK" should happen is:
-I get the normalized direction to reach the player
-Then I multiply it by the distance, but since that would just give me the player position I shorten it by 2
-After all that I just use Unity's moveTowards function
This is a code channel. Check the error in the console
"FSBTool ERROR: Encoder for chosen format is not supported on this platform."
Start by googling that
Mind wrapping ur code with a code block
Also what is happening instead
rb.linearVelocity = Vector2.MoveTowards(transform.position, endPoint, speed * 100 * Time.deltaTime);```
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ohhh ok
Vector2 endPoint = transform.position + (player.transform.position - transform.position).normalized * (Vector2.Distance(player.transform.position, transform.position) - 2);
rb.linearVelocity = Vector2.MoveTowards(transform.position, endPoint, speed * 100 * Time.deltaTime);
Instead it gets away from the origin point exponentially faster
Might wanna check the doc for how MoveTowards actually works
so you're using MoveTowards and you feed it 2 positions. you get a position out.
then you assign that to a velocity
Currently you seem to be plugging a position to a velocity
also that endPoint seems a bit... overengineered?
I did that
yeah do you see the issue with that
A bit unrelated but is that endpoint formula the lerp formula?
doesn't look like it
No just a thing to get a point in the direction of the player
But I understand now, I was just being dumb
player.transform.position + (player.transform.position - transform.position).ClampMagnitude(2)
```i think this gives you the same result (at least if the distance is > 2)
if the distance is < 2, your original code would make the object walk away from the player
this version makes the endpoint the object's current position
I think the endpoint should be something like cs Vector2 directionToPlayer = player.transform.position - transform.position; Vector2 endPoint = player.transform.position - directionToPlayer.normalized * 2;
If you want the endpoint to be 2 units away from the target, while keeping distance
yeah osmal's version keeps the same behavior
different magnitude calculation for the offset
your existing code/osmal's sets the magnitude to 2
mine clamps the magnitude to 2
but overall same idea
Yeah my version keeps the distance, so if it's < 2 units away then it would move away instead of towards the player
i googled it and i got no results
like, it doesn't tell me how to solve it
mp3,wav, or ogg doesn't work idk why
yeah but i get no response
Then wait, and also share more details like what platform your editor is on and what platform you are building for
im interpreting lua using moonsharp and trying to make it draw text on the screen. it adds a (string text, Vector2 position) item to a list of them and OnGUI scans through the list and draws each text. BUT if i clear the list at OnGUI, Update or LateUpdate the text simply doesn't draw at all. could someone help me thru this?
was meant to put that in #archived-code-general oops
nvm i got it to work
turns out it only took 5 misspellings of "oops" to fix it
Mmmm.... why this error? None of these objects have a RectTransform, they only use a sprite Renderer
I cannot even call that method lol
you sure it's from that line?
also of course you wouldn't be able to call the method, you wouldn't have anything typed as a RectTransform there
Quite literally I am clicking on the debug line link
it's pointing to the transform.parent = ... line?
Yes
None of these objects have a RectTransform
validate this assumption then, try logging all the waypoints
just something like Debug.Log($"{waypoint.gameObject.name}: {waypoint.transform}", waypoint.gameObject); in the loop
Wait, wtf, THEY ARE. They were normal transforms before, 100% I even took the reference of their possitions to set the default possition
I don't even know how to do that if I wanted to
Did you make them children of a canvas at any point
I think I may have added a Canvas to them by mistake at some point
But the rectTransform stayed there even after the removal I suppose
Can I even change a rectTransform for a normal transform?
Remove the RectTransform and it'll revert to a normal transform
Oh, wow, surprisingly easy
Oh by the way, is there anything I should do in VS to make it easier to use or anything? I turned on the error box thing at the bottom last night, and I'm wondering if there's any other like must haves
Have you configured it? !vs 👇
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
how do i make it so my script disables the mesh renderer of the object that its on and not the whole object?
Just disable the mesh renderer. And not the whole gameobject🤷♂️
It's like "how do I eat apple and not orange". Just don't eat orange🤷♂️
i need the script to disable the mesh renderer after a set amount of time. how do i reference it
Well, how would you reference any other component?
question. is there a means one can programatically exit a unity game without too much issue?
idea is a 'blank' unity game who's only purpose is to exit itself for benchmarking purposes.
thank
Assuming I can just plop that into a game object in the default scene?
I really wish I could use something like the animation state machines to manage my boss attacks
You can . . .
how
I couldn't find anything by searching "state machine" on the docs
Only the animation controller
A tutorial uses the animation state machines for an actual state machine. Use Google instead of searching the docs . . .
Okay I'll check that out
There are pros and cons to using it. I can't remember (them), but the video should have all the info . . .
Is it "finite state machines"
If you want to use the animator for a non-animation statemachine, you need to look into StateMachineBehaviours