#💻┃code-beginner
1 messages · Page 687 of 1
in luau we would do it using signals, where Update would be a signal you can connect a function to, is there any similar concept in unity?
Whether you doing this yourself, or use some event system, is just a structural thing.
If you're not checking it every frame how is it supposed to know it shouldn't do the thing any more
if statements
Yes, signals in this case would be events I'd imagine.
But even that is still checking "all the time" under the hood. You just don't see it, which is probably why you feel better about it 🤷♂️
well an event happens when i want it to start and when i want it to end, and i would just connect and disconnect the function right?
You could invoke an event every frame, and just subscribe or unsubscribe from the event but null-checking an empty event and calling them is even more process intensive than checking a bool
The correct way to do this is to set a boolean and check it in Update. That is the least obtrusive and most performant way to do what you want to do.
damn
Every other ways is less intuitive and a higher performance cost
Checking a boolean is literally a single CPU cycle. It would take four billion of them to take up a second of processing time
signals are worse on memory but don't have to check every frame they just run through an array of connected functions every time they are called
Looping through an array is significantly slower than checking a boolean that many times
theres really nothing similar in unity?
Nothing faster than an if statement
wow
Why are you so fundamentally opposed to an if statement. It's the single most lightweight operation you can perform in code
so if statements are super fast in c#?
if statements are like 3 instructions
Is it even worth nothing to do a complex FSM if the game (2d) is purely for practice?
idk cause in my head its code running that doesnt need to
If statements become je or jne
but if this is the way then i will do it
But it does need to, otherwise you wouldn't be writing it
You could use it to practice complex FSMs 
well no they'd be a cmp + beq/bne
there would still be the cmp
Ah, right. Two instructions. Two billion if statements to reduce your FPS by one.
(im being pedantic, of course it doesn't matter)
Right, still a fair assessment
Time.deltaTime
no, it's accessible statically ^
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It is the amount of time in seconds the last frame took to execute
so variable
ok wait from a physics perspective should i be using this delta time value
or will a force mode of force resolve this?
For physics you should be using FixedUpdate and FixedDeltaTime
alright cheers
A tool for sharing your source code with the world!
@sharp solar fyi though - even though going through an array is comparatively slower than doing the direct check, it's still a tiny amount
let's say you have a 2 GHz processor that takes, idk 8 machine cycles for each instruction, being extremely generous
that's 4ns per instruction
an if on a bool would take 3 instructions - load bool, cmp, beq, 12ns
an if on an array would take 6 instructions - load array, load index, add, load value, cmp, beq, 24ns
plus like, 3 more for iteration, load index, add 1, set index, for +12ns
it's 12ns vs 36ns
at 10000 bools, that's 120us vs 360us - still far below a single frame, at 500 fps a single frame is 2ms
if you're using Force, don't use deltatime at all
it's applied automatically
thank you for this knowledge
roblox is such a letdown in almost every regard now that i've seen the light
Real🙏
That was my starting language
Where can I buy game
ive been on it for 4-5 years now and fed up when i ask for a simple bug fix after making them thousands of dollars just to get no response after months of bringing it up then when i say im fed up with not getting a response they remove my post
done
Wow 4-5 years is pure dedication
so i linked between the PlayerCamera class to the class named PotatoMovement(dont mind shitty names i am testing out random stuff). so i think i managed to call the functions correctly. but now i am wondering about the variables, like sensX and sensY. is it possible to add them in PotatoMovement and add SerializeField to them?
yeah cause i lied
3-4 years
i remember dates wrong
Still dedication
chat, i copied this from 5 different youtube tutorials, is this good?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5.0f;
private Rigidbody2D r;
private float horizontal = 0;
private float vertical = 0;
private Vector2 moveDir = Vector2.zero;
private List<string> moveHistory = new List<string>();
private bool canMove = false;
private int frameCounter = 0;
private string lastKey = "";
void Awake()
{
GameObject obj = GameObject.Find(this.name);
if (obj != null)
{
if (obj.GetComponent<Rigidbody2D>() != null)
{
r = obj.GetComponent<Rigidbody2D>();
}
}
}
void Start()
{
StartCoroutine(DelayStart());
}
IEnumerator DelayStart()
{
yield return new WaitForSeconds(0.00001f);
canMove = true;
}
void Update()
{
frameCounter++;
if (canMove && frameCounter % 1 == 0)
{
if (Input.GetKey(KeyCode.A)) { horizontal = -1f; lastKey = "A"; }
else if (Input.GetKey(KeyCode.D)) { horizontal = 1f; lastKey = "D"; }
else { horizontal = 0f; }
if (Input.GetKey(KeyCode.W)) { vertical = 1f; lastKey = "W"; }
else if (Input.GetKey(KeyCode.S)) { vertical = -1f; lastKey = "S"; }
else { vertical = 0f; }
moveDir = new Vector2(horizontal, vertical);
if (moveHistory.Count > 9) moveHistory.RemoveAt(0);
moveHistory.Add(lastKey);
}
}
void FixedUpdate()
{
if (r != null) r.MovePosition(r.position + moveDir.normalized * speed * Time.fixedDeltaTime);
}
}
I was on it for like 1.5 years
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry, i hit enter too quick
but its work
somehow
Don’t do yt tutorials trust me do thr Unity junior programmer tutorials
Otherwise you won’t retain the information as easily
Looks perfectly fine. Is it working as it should?
One thing at glance is that Start can also be an IEnumerator directly. So you can do
IEnumerator Start and skip the StartCoroutine(DelayStart()); and just run your iterator directly
do you know what it does or how it works? if you do then its fine. just dont rely on them, since most of the time they are unreliable
Variables are not shared between scripts just because they have the same name. You could set the variables on your _playercam variable since they're public
@fallow wind
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
could you give me a example how to set them?
=
with tutorials just make sure youre working toward something you want and youre not just observing you're trying to come up with your own solution as you go and it's fine
oh, dont mind my dumbass.
watching is bad, doing random tutorials is boring
The junior programmer one is peak it actually teaches u each common piece of code used in c#
i thought you meant it in smth else, like lets say my main class Player Camera i want to use it on multiple other classes/scripts beside PotatoMovement and i watch each of the other script to have a diffrent value for sensX and sensY. is something like that possible?
Are they all referring to the same instance of PlayerCamera
Then there's one instance of PlayerCamera. It has a sensX and sensY, which will have whatever value they were last set to
int x = 7;
x = 4;
x = 12;
Debug.Log(x);
What do you expect this log to print?
It's the same principle.
Oh i see
Tysm for the simple explanation
what is an object for you in roblox
short answer yes
A class is a blueprint for a thing. It defines the functions, variables, properties, etc. that an object can have.
You can create instances of a class to make an object that uses that blueprint. Those objects are individual elements of that class with their own copies of all of the variables and whatnot.
when i put a script inside a game object is it essentially creating a custom component?
component whos class is defined by the script
Like, a class is "The platonic ideal of Cat". It has variables for name and color and functions for DoMeow() and KnockShitOver(). An individual instance cat is named Ollie and is a Black Cat and when he meows it sounds like a smoker's cough and is an adorable bean
i am leaving google at this point, i had a ad tahts 3 minutes long and the video is 9 minutes... so a dd thats 1/3 of the video
When you add a component to a GameObject, it creates an instance of that class on that object.
ye, but just remember the component is an instance of that class/script, not directly the class/script itself if you know what i mean
yes
its a "component" because its inheriting MonoBehaviour which inherits Component which inherits UnityEngine.Object which is the base of class inheritence
so it goes without saying unity is very object oriented
Most modern programming languages are
is there types in c# or just classes
can you make types
Yes, that's what you're doing every time you make a class or struct
that response sounds like you might have a different thing relating to the term type
types include classes, structs, interfaces, enums, delegates, array types, primitives, and generics
a type to me is a thing that a variable is assigned so autocomplete knows what to do lol
i mean a type is just what something is
a variable isn't assigned to a type, a variable has a type
thats what i meant sorry
Someone smarter might disagree with this specific wording but its pretty much just an identifier
just so you can point your finger at an object and say "thats a human" / "i want a human here"
yeahhh so identifiers have a specific meaning
every time 
in luau types are more of an optional thing that you use to assist typing out code which is where the confusion lies i think
quick question, is it possible to have sensX and sensY instances in PotatoMovement. privated, like if i ever edited the one inside of PotatoMovement. it doesnt affect any of the sensX and sensY outside of it? and could you provide a little example related to my problem if possible? if not possible its fine
yeee in most cases we are very explicit in what things are here
imo it's very preferable
types always exist - luau just doesn't have them (required) in source code
Every instance has their own copy of every variable
and how can i access them and modifiy them. cause i kinda forgot how(sorry 😭 )
...by name?
... how... i keep getting bunch of errors
what are the errors
using the name you gave them
or do i just write the entire thing
That's what the name is for
what "entire thing"
To serve as the thing you type when you want to use that variable
[SerializeField] float sensX = 5f;? should be like that or am i thinking wrong
So you would access this variable by name, sensX
how do I add a value to a list
.Add
so hopefully this is correct(prob not). so i went to the inspector and filled up the stuff. but those functions aint working, i am getting errors. i think those functions are still reading from main class instead of this instance, any ideas?
what .add?
What are the errors
you never assigned a value to it. Hows the computer supposed to know which PlayerCamera you want to run those functions on
i did that from the inspector, isnt that how it works?
how did you do that in the inspector when the screenshot showed it was not even public or serialized
also the error isnt even this script you showed
the error is on PlayerCam not PotatoMovement
What is the line the error is on
my sensX and sensY are public tho... including the oreintation
that's not what's erroring though
@polar acorn @rich adder any more information needed?
Which line is the line the error is on
also don't use deltaTime for mouse input, it's already per-frame
27 in the PotatoMovement which leads me to the earlier screenshot, the script i sent i believe its fine since i tested it
ah sweet, noted
inside PlayerCam.cs
Line 27 of PlayerCam?
The line the error is on
wait, PotatoMovement is in PlayerCam.cs?
Exacly
i was gonna type that
ruff
that's horrifying
Don't
welp, what nav said - you never set _playercam
i am testing so yeah, my code is really fucked....
Don't put two classes in the same file
wow thanks unity for taking out the error of filename and component not matching..
no, "testing" should not result in this
its just 1 class... but i renamed it...
good point, after i figure out this last piece i will fix this mess
is there any lib i should import for random?
😭
UnityEngine
Unity has their own Random you can use . . .
Okay, so the file is named PlayerCam
i got like 5 playcam stuff so i needed to rename one so i can diffrenciate cause i didnt know what was the use of each one
it will tell you why.. its probably because you have the
Systemnamespace and its confused on which Random you want
yes and the class inside of it is potatoMovement
But the class is PotatoMovement
yes..
So then if that line you showed is that file, then _playercam is null
(they were redirected here)
Did you check what the error actually says
so this is wrong
oh wops. didnt see those , had that person blocked for some reason lol
not necessarily wrong
i did rn mybad
Where do you assign a value to it
so you lied
You should always lead with, show, and read the error . . .
oh... so i should use get component
you should do something to give it a value
thanks <3
You would need to actually assign a value to this variable
i thought we were talking about the values of sensX and sensY
you have to tell it which PlayerCamera you want that variable to hold a reference to
those are value types, they don't throw null references... they are just numbers..
oh 😭
assign it in the inspector or use = to set it to something
that might be via GetComponent but we don't know your context to know if that'd be applicable
noted
in most cases you want to do it in the inspector
-# well to be pedantic reference types are also numbers
truth
could you give me a quick example on how to do it so we dont spiral down on another maze
noted aswell
but i will try to do it via script
look up the method they suggested, in the docs then
here a neat GIF too from unityhuh site
i meant inside of a script, the get component one 😭
Is the component you want on a different object
no its just this, but you said if i did it using the get component way correctly my problem would be magically solved since i wasnt instantaiting correctly
so like this?
What object has the PlayerCamera you want this variable to reference
instantiation doesn't really have anything to do with this
have to start taking chances as a dev and
things on your own
i didnt get it....
This variable is a box. The box has a label on it that says "For FirstPersonMovement.PlayerCameras ONLY! 😠"
You have to actually put something in the box. Which FirstPersonMovement.PlayerCamera do you want to put in the box
i mean... i dont know what exacly to put inside of it
Which PlayerCamera component do you want to reference
When you call _playercam.MouseLocking(), which PlayerCamera do you want to call MouseLocking() on
Watch this video in context on Unity Learn:
https://learn.unity.com/tutorial/scripts-as-behaviour-components
What are Scripts in Unity? Learn about the behaviour component that is a Unity script, and how to Create and Attach them to objects.
the instantiated one
Where are you instantiating it
hold on let me watch this so i can understand without asking too many questions
Playercam Script...
Show where you're instantiating it
FirtPersonMovement.PlayerCamera _playercam;
_playercam = GetComponent<PlayerCamera>();
...wrong?
None of these are instantiating anything
FirstPersonMovement.PlayerCamera _playercam is creating a variable that can hold a FirstPersonMovement.PlayerCamera.
_playercam = GetComponent<PlayerCamera>() is setting the _playercam variable to the PlayerCamera component on this object.
Does this object have a PlayerCamera component on it
and I think instantiating is probably not what you want to do anyway. iirc, instantiating would be to create a gameObject from a prefab that the script sits on. Get component would pick up an existing one off the same game object. new() would be to create an instance of a class that is not a monobehavior. and for monobehaviours... i can't remember the syntax, but there's something like AddComponent<>(). I think
slight correction, instantiate doesn't need to be with a prefab.
in unity it just clones an object basically
but in this case, I think what you'd want is to add the PlayerCamera script to the game object in the editor, then use a GetComponent call in PotatoMovement to set your _playercam reference variable
ty ty
I think they don't actually know what "Instantiate" means or what an instance even is so I don't want to start going into solutionizing until they've actually managed to sus out what it is they actually want to happen
Otherwise it's just going to get confusing.
Chances are, they do want to do this, but at this point we aren't actually sure what the intent is
mhm. fair. I'm just hoping to lay out some definitions at least to help clear things up
I'm not sure if they're trying to add a component or reference one that already exists
oh... i see, i think i got a idea on what to do
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi Guys,
Does unitywebrequest work like coroutine and on main thread? I have to download 6-7 glbs . Not sure if i should use c# native httpClient or unitywebrequest.
I heard UnityWebRequest is executed mainly on main thread.
Dont want to make the game stutter during the downloading (i dont trust coroutine based behaviour for performance while downloading large files paralley)
If i can offload the download to other threads then all good
for my web request, I was just using Task / Await which is on the main thread, but it's not a giant download like that, so I can't say how that would go...
as far as I know, the job system is the only multi thread option in unity, and it doesn't talk all that well with the main thread, so i'm also not sure how handing over 7 gb as a return type would go
sorry, its not gb i mean glb format
total around 150mb max
If i couple HttpClient with UniTask then will that be better?
I feel unitywebrequest use coroutine under the hood.
no
Hey guys, sorry for the stupid question but I'm trying to write a simple function to convert a position from world space to local space in a simplified way that assumes the local space of a logged transform always has a y and z axis rotation of 0. The problem is that I'm having alignment issues with the results and I honestly have no idea how this is happening. It's almost like its assuming the angle of it is slightly off?
{
Vector3 localPos = worldPos - origin;
Vector3 flatPos = localPos;
flatPos.y = 0;
return right * flatPos.x + forward * flatPos.z + new Vector3(0, localPos.y,0);
}
Here's a clip of what isn't working. The Cyan Sphere is the base/anchor transform, and I'm trying to convert the yellow spheres position to its local space. The green line is drawn between what the function above is returning to me and the yellow spheres position.
Any help is greatly appreciated, thank you
For probably easy problems with code i just post the code here?
webrequest is optimized for unity, read somewhere a while back that it was threaded
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.SendWebRequest.html
returns a WebRequestAsyncOperation
nice
sure but shouldn't be a replacement for google which what a lot of people do
you may be overcomplicating this. is the yellow sphere a child on the anchor? or is it a spawnpoint for future children of the cyan sphere? in most cases you could just take transfrom.localPosition. outside of that, there are prebuilt functions for converting worldspace to local and back
it's intended to be used in a lookup table for culling optimisation purposes, this is a simple test of the function to make sure it returns the correct value
probaly i will find a solution on youtube or google , but I dont even know the problem
I was originally using InverseTransformPoint but I realised I could make optimisations to cull unseen building faces
ah ok. in that case
i will look a little closer at your snippet
how are you passing in right and forward?
it concerns me that your green line moves when you rotate the cyan sphere
what is happening vs what you expect to happen ?
I want that that button moves my triangle, and it worked, until I added mirrow and suddenly it stoped working
mirrow?
what is mirrow
you're doing multiplayer ?
also you never use the entirety of flatPos, so you don't need to set its y component to 0. in fact, you could just use localPos
i am trying to
I don't know why, but instead of using the anchor transforms actual transform.forward and transform.right, I create a rotation Quaternion.Euler(0, -anchor.EulerAngles.y, 0) and use the Vector.forward and Vector3.right of that and it works now
just switching the Y angle of the anchor seems to have fixed it?
*or flipping it
you're in code-beginner asking about multiplayer lol Should you be doing that already?
no it's thedifference bertween using transform.right and vector.right
if you comment out he quaternion line, the second one should still work
the second one does, the first doesnt
yeah
wouldn't testAnchor.forward be the same as testAnchor.rotation * Vector3.forward?
I know how to code, but I'm learning unity new. I don't know how thinks work with buttons, prefabs, skrips,...
ohhhh, I see. maybe. huh....
thats like the most essential part about doing a multiplayer part here..
well ok..
no one can help if you're asking
"i add package and is broke "
and using -testanchor.forward and -testanchor.right doesnt work either so
I have literally no idea why
but it works...
just out of curiousity, if you only pass in vector3.forward / right without the testRot, what happens?
completely boned again
cause its basically assuming the transform has a rotation of Quaternion.identity
unity is wholeheartedly convinced that there is a missing script on this object, when it is most certainly there. no other objects named door exist in my scene, and this is the only script the door is trying to reference
anyone have an idea of why it might be doing this?
when i click on the script name in the component area of the object it highlights the correct script in the project area, meaning it definitely knows its there.
for context, this started as a prefab from the asset store. I removed the old script component on the door, and added a new script component with my own script. It seems like it just wont forget about this deleted script component
i hate unity
its hard asf
im thinking about giving up on game dev
what should i do
what do you find so hard?
delete all those messags from here, and stick to #💻┃unity-talk
!warn 1231260241476456609 Don't spam multiple channels and don't post off-topic. Read #📖┃code-of-conduct . You've been provided with links to resources already.
yaya098009 has been warned.
It says referenced script. something else is referencing old component of yours
Can you show the full inspector of the Door object?
And also the prefab
here is the parent object (door_1_venge) and its children
it is definitely something within this parent/children, i just dont know where
Well, this is Door_1_Venge. The error says it's on an object named Door
door_1_venge is the parent of door.
So show the inspector of Door
Oh, there's a lot more images than thumbnails, I didn't scroll far enough, my bad
no youre fine, sorry for the image spam there lol. i know discord doesnt make it easy to see
Well, this Door object looks to be fine. Is this the prefab, or an instance of it in the scene?
may as well add - this is the tree for it
so im pretty new so ill describe what i did and hopefully that answers the question.
I dragged this prefab onto the scene from the project area, i deleted its script on the object in the scene, and then added the component for my script
heyo i'm working with gltf to load a model into the scene
private void Import_GLTF()
{
string dir = "actual/folder";
string filename = "file.gltf";
Uri uri = new Uri(dir);
string uriString = uri.AbsoluteUri;
var importOpt = new ImportOptions();
importOpt.DataLoader = new UnityWebRequestLoader(uriString);
var import = new GLTFSceneImporter(filename, importOpt);
Task gltf_import = import.LoadSceneAsync();
}
this goes on in the background without await so it doesn't stop the user while it's loading even if it's a big model
how would i exactly get the percentage complete from a task?
i can't cast it to Awaitable or Addressable to get that value, how could i approach this in general?
all i could find uses awaitable or addressable and can't cast to either
Okay, so the screenshot was of the instance in the scene. The Prefab itself might have the missing script. Open up the prefab and check there
ah it does, so if the original prefab relies on that script, i will get the error even if i removed it on the instance in my scene?
Something is likely still looking for that script which no longer exists. If you're removing it from the prefab every time you spawn something, you should probably just not have that script on the prefab in the first place
yeah so far this is just the initial drop of the door, so i was testing things before making changes to the prefabs themselves
lemme see if this fixes it
that did, appreciate the help.
thatll be an interesting hill to climb when i end up in a situation where I need a one off on a prefab with a different script lol
The issue isn't that the prefab has a script that the instance doesn't - it's that something is still expecting that script to be there
So, something else is referring to that script, probably within that prefab
How do I save player's level completion time and load it in the main menu?
You need to store data by saving and loading to a file . . .
extremely new to c#, this is the way i was able to make movement but with the addforce thing itll just keep on adding up and build momentum until like infinity pretty sure, so is there any better way i can learn to do this?
to any ppl experienced in coding with unity this codes prob gonna look really bad lol
Are you wanting non RB movement?
just any sort of movement
i was originally gonna change the co ordinates every frame but i just messed around with rigidbodies instead
If you're wanting to use RB for collision detection the common choices are to:
- Move using velocity (6.0: linearVelocity)
- Kinematic RB (create your own physics but still have some RB features - moderate to difficult)
i originally tried it with velocity but for some reason it wouldnt move when going to the side, im assuming it has something to do with the colliders
bad code space program (spamming space)
Hello I need some help. I am a total beginner with some coding background but still very much a novice. Trying to add a player movement script to a player object as a component while following a guide on yt. I keep getting this error "Can't add script behaviour 'PlayerMovement'. The script needs to derive from MonoBehaviour!" and am not sure how to troubleshoot.
i think u made a non monobehaviour script
if u made one it should show in brackets on the name in inspector
So one thing with this version of unity is there are a bunch of options in the create > script options and it was confusing. I chose "empty c# script"
yea ur gonna wanna click this one
Ah okay I will try that, thank you very much
if I wanna save data in relation to a specific scene (e.g. time on stage 1), would it be better if I use dict or using two lists?
Maybe something like this would suffice for horizontal movement and a jump mechaniccs float x = 0; if(...)//Right held x += 1f; if(...)//Left held x -= 1f; var velocity = rb.linearVelocity; velocity.x = Mathf.Clamp(velocity.x + x * speed * deltaTime, minSpeed, maxSpeed); rb.linearVelocity = velocity; if(...)//Jump rb.AddForce(jumpForce, ForceMode.Impulse);
Dictionary can't be serialized as-is, so if you play on saving it to JSON or some other format then you'll have to do it as two lists (keys and values), or saving the key-value pairs as structs
I'm currently following this (https://www.youtube.com/watch?v=XOjd_qU2Ido), would it be better if I do it in JSON and pivot now or is the tutorial still fine
Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.
● Easy Save: https://bit.ly/2BzgdXb
❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU
················...
I suspect the tutorial is fine, but I don't have time at the moment to watch it all
ah ok, it'slike a 6y/o tut, and it made no mentions to JSON so i was a bit confused
JSON is just one possibility, you can save in many other formats
Just don't save to playerprefs
Oh yea I heard about that
First piece of advise of saving "NEVER USE PLAYERREFS" which i heard in some video, pretty funny
PlayerPrefs is fine to use for some saving that isn't a big deal, but most save data, you should avoid it
By itself though, not a great utility, if you build a parser for many types and use that to save to playerprefs for non-trivial data, then it's fine
It has one downfall of being messy. You can always delete files you save in most formats, but playerprefs goes to your registry which is not as simple
Yeah, definitely more messy, not a preferable option
it most definitely can be serialized as a dictionary @shut swallow
https://www.newtonsoft.com/json/help/html/serializedictionary.htm
Guess that's a new addition since I last looked, as a few years back everyone was writing their own serializable dictionary substitutes that were two lists or structs under the hood
I am looking for some pointers on the most appropriate way to avoid my player (rigidbody) getting stuck on walls in my 3d scene. I've tried setting the walls friction and bounciness to 0, and this has stopped my issues with getting stuck, but has introduced weird movement with steep slopes where the player is able to walk up slopes they definitely shouldn't be able too. Is there other solutions to the problem that fix the player getting stuck on walls without breaking slope movement?
How do you make a custom cursor with special vfx without it lagging behind?
FindObjectsOfType<MonoBehaviour>() how do I rewrite this with the new FindObjectsByType, I just replaces Of to By and it didn't work
what do I pass as object?
looking at the docs you need to pass it the sort mode to use
FindObjectsSortMode.None
pass the type as a generic so in the <>
I still don't really get it sorry, elif
FindObjectsByType<MonoBehaviour>(FindObjectsSortMode.None)
I thought type needed to be declaired within the method
it supports both
but using generics is better since you get the proper return type without a cast
to pass it as a args you need to use typeof
FindObjectsByType(typeof(MonoBehaviour), FindObjectsSortMode.None)
any reason to use args over the generic?
weird and probably unideal situations where your passing through a type via a param/value and can't explicitly define the generic usage
doing it via args can make sense in some edge cases
like if you got a type via reflection
for most cases if something needs a type and supports generics use that over passing it as a regular arg
Also not directly saying don’t do it that way but findobjectoftype calls are pretty heavy and iterating through every monobehaviour conditionally casting is probably not great either at scale
99% chance you are better off doing the reverse of this, having those objects call a manager and pass themselfs to it
And if for whatever reason these objects toggle their gameobject activity that search won’t find them unless you specify in the findobjectsoftype param that you wanna find inactive objects
then you get a collection that only contains stuff you care about without searching every component in the scene
Though there's not particually a great way to do this in the scope of the interface right?
I guess that's somewhat by design but
my suggestion would work with components that implement the interface just fine
fair, i just meant that the component has to explicitly handle the giving that out
yeah its that or searching alot of objects
i very commonly have things that on Start will notify other systems about themselfs oftne just calling a method and passing this
and due to covariance it will work even if its accepting it via interface
yeah same. I think i keep wanting interfaces to do stuff there not meant to do and i get dissapointed when they cant aha
would be "nice" to get a interface function running on object creation without needing the thing implementing it to "manually" call it
they do most things i want, only rubbish part is not working with SerialzeField
but i also don't really use components unless i have to, so a lot of systems are just regular C# with regular objects
i over-use default implementations but one thing i would really like is a way to override default implementations from a inheriting interface
yeah i do not use default implementations for the most part, feels like fighting what interfaces really are
probably
idek what's an audio listener, how do I solve this
usually they on cameras iirc
it's a component to listen for audio, check your cameras for it because that's where they usually are at
for anyone else with a similar issue, i was able to solve it by keeping the friction at 0, and raycasting near my players feet in the direction they are moving, if the angle of the object they are moving into is greater than my max slope angle i disable movement in my movement controller. Now if a player lands on a slope they slide down it.
Still wondering! Thx
depends on what you mean by lagging behind
and special vfx
assuming it's just an image then just setting the image's position to the mouse position in update should work fine (i dont think it'd lag behind a by a frame but im not 100% sure)
is garbage collection automatic in c#
it's to stop Euler locking
reminds me i also need to look into quaternions some more. i still barely understand them 
im hoping through functions i wont have to understand them lol
A tool for sharing your source code with the world!
I finally added 5 second cool down after using jump
is there any difference between Awake() and Start()
can you access unity hierarchy through a script during runtime instead of setting public variables beforehand
the more you know :D
not sure, usually you'd just use one of the many Find~ methods to get the object you're looking for
oh ok
Now i wanna learn how to connect different scripts and use methods from anothet script
But i dont wanna push too fast. tho i should practice what i learn recently
usually you'd have a script as a component on an object and then you could reference the script in the editor by passing in the component.
i discovered UnityEvents pretty recently though and they've been so useful (UnityEvents my beloved)
oh yeah that's fair. learning at your own pace is always best
you generally dont have to worry about the gc yea.
these are questions you can easily google. this channel is more for questions you're actually stuck on rather than a replacement for google
true
Chatgpt deepseek and unity documentation manual scrip page
U can learn everhthing with these 3
Just be aware that ai can give u wrong answers sometimes
U need to check documentation first then ai to see the end of tha road mate
😁
😧
❌
I learned everything with tha ai and unity documentation bruv
yea
I tried youtube and udemy but it didnt worked for me
youtube sucks
u learn how to make the thing they are making but u dont learn how to use unity
(that was my experience with roblox lol)
Sometimes works. If i didnt understand with ai and documentation i go google and youtubr
Last chance
AI is pretty cracked nowadays
wasn't really a thing last time i had to learn something
Yep.
I just learned basic language syntax and i asked ai and copy paste code blocks and edit it like that until i solve the issue
Ai doesnt give me the full answer most of the time on coding
I have to edit it
But ai shows u the road very well
About which techniques u should use
Maybe im wrong but i feel like it works 🤣
Ai is good for learning unless you just mindlessly copy and paste
all pretty bad advice tbh. if you want to read/comment on the use of AI, there is a forum https://discord.com/channels/489222168727519232/1352599815770341479
a bunch of beginners telling each other AI helped them learn definitely isnt the best advice you want to be reading from.
am only a beginner to unity***
I tried udemy youtube those were the worst than ai for sure
I rather use ai than a university student acting like he is computer engineer professor
yet i never suggested udemy or listening to these university students. dont suggest others to use AI at least. It's highly discouraged here
A couple of reasons why AI isn't good to learn from:
- It makes mistakes that you may be unaware of
- It uses strange patterns and do not really understand what it's doing
- It's convincing
- It lies
- Dependency issues
A couple of reasons why AI might be useful: - Pretty up code you've already written (documentation, syntax etc)
- Draft prototypes that are tedious to write
Personally, I'd use it like a work horse to brute force simple tedious tasks.. if anything.
It's not very fun to fix mistakes that aren't relevant and can lead a beginner down the rabbit hole if they aren't aware that it's wrong/lying.
While I would agree with you I really would not recommend AI at all when it comes to beginner programming of any scale
It takes a specific mindset to actually learn from AI, and most people don't have it in them to actually understand what is written and how it is written, especially here.
And also because it can be confidently wrong, meaning you need to ensure that your knowledge and/or research skills is good enough to understand if the code is good
It's all too common where a beginner will see any positive feedback about AI and decide to continue using it for everything regardless of how many negatives you list.
Though the worst is the case above where a beginner who clearly started recently says they learned everything through AI. "Everything" being very misleading when they said they don't know how to reference another script.
i recommend ai
even professional coders uses it
no need to avoid it
its useful sometimes but yea it can give u wrong answers
repeating points while not addressing the responses isn't going to go anywhere. plus i truthfully dont care to convince you otherwise at this point
Dont take it from me then, mods have given the same advice about not suggesting people to use AI
#1319020501250740315 message
#archived-game-design message
well i just told u ai and unity documentations helped me alot
and i told you that ai can give u wrong answer and u need to edit it
Yea you clearly arent reading what I'm writing if you're still just repeating stuff you said from above.
I'm done here
As i pointed out above, there is also a forum for AI discussions
is it forbidden to recommend ai
it's a debatable question. AI is still a very new thing and it's still at the point where it's improving by the day.
imo it's just down to personal preference although solely relying on it is definitely going a bit too far. using the general standard is usually the safest bet and thus the only one you can really recommend.
yes i agree
yes, this discord server is for learning and AI is not good for learning at all. people who use AI for learning will lean in to just having AI code everything for them, and they won't develop the skills to research what they're looking for and debug code, the most important parts of being a developer
when you go out to work you realise that you won't know everything, and you'll be using libraries that just have next to no documentation. your AI won't be able to help you anymore and you're expected to live without AI
im using unity doc ai youtube google
and yes I've had to personally guide colleagues who are like this
this is a silly conversation
i dont wanna work as a coder tho. i just wanna make my own small game
so you don't wanna learn coding and just have us debug for you
people here are going to naturally gravitate toward pro AI or anti AI mindsets and whether you should or shouldnt use AI is highly opinionated. just do what you want, it's a tool, no need to push your beliefs onto others
well im just started learning coding
i agree
Your experience with AI is not the same as what others will experience. Beginners resort to being spoonfed answers very frequently and especially AI is a problem as it will give a lot of code with possible errors that just resorts beginners to come back here and ask what's wrong with it.
if you don't work in a programming role then ok I guess but just try to understand what the AI is giving you
We're not against AI, we don't need people suggesting AI to beginners because it won't work for them
this channel has been flooded with people asking us to debug their AI generated code
in my own experience. i tried to learn coding in the past too much and i always failed and i gave ai chance and i liked it with the help of unity documentation
I'd rather eat bricks personally, but you do you
And also flooded with beginners spitting out the exact same talking points while barely reading the actual responses.
Ive directed to the ai discussion forum twice already lol
It's just not nice to ask other people to fix code when the person doesn't even know the fundamentals of coding
yeah. it gives wrong answers most of the time and im searching on the internet to find correct one
Which is what beginners do not do
AI isn't good at debugging imo, like you tell it "oh I experienced this error please help" and it will not help you to fix it
They come here, often after many failed attempts of editing the code and making it worse
If someone says they used AI and have come here for help it's a great invitation for me to do something worthwhile elsewhere
i dont copy paste code without understand it. im searching on unity documentation youtube google to see if its logical
if its logical i copy paste it
well "using AI to write code that you don't understand, then make it worse, then get someone to fix it for free" is objectively a terrible thing to do but in my opinion using AI to learn stuff is fine
Happens in this channel daily
@formal tide Trying to learn from pre-chewed responses of LLM is very counterproductive. By not looking up things in documentation and using structured courses you are severely handicapping yourself.
But that's up to you.
Here, like you've been told already, don't send people to AI or talk about it really, it's off-topic.
pasting a block of code and saying "fix it" is annoying in general in my opinion
this happened before AI too
i never said i dont look up thing in documentation sir
i use all of em
jesus
Then drop it already
i didnt know ai was hot topic like this
in this guy's defence, they have said a few times that they've been looking up documentation to double check.
they have actively been reading any documentation that's been shown to them in this channel.
they seem to be getting dogpiled a bit here due to how controversial the topic is.
more specifically the dogpilling was more so in response to the endorsement of ai rather than acknowledgement of usage
it's not hot topic, but abusing AI without learning from it might get you no where, at least thats what people here is trying to say, I guess...
its a hot topic
and more that the user is suggesting that beginners can rely on AI to teach them things without developing developer skills is a bad idea in general
Most of us here are volunteering our time helping others, and picking up where AI left off with people who aren’t actually interesting in learning rubs most here the wrong way.
It’s nothing super specific to AI as much as it is trying to respect people’s time and effort. Presenting a problem is different from presenting incorrect AI replies asking what’s wrong with it.
yep u shouldnt rely on ai. always use unity documentation as a source and then u can use other sources as well 😄
To me it's just an insulting thing to suggest as a starting place in a place full of developers who spend their own time here helping others.
Not because of how controversial it is. Because they are repeating the exact same points multiple times without actually reading what anyone is saying.
Not to mention, stuff you get from LLM is the average terrible code it scraped that you are learning from.
i understand ur hard work and i appreciated. i didnt know recommending ai was disrepectful
what type of question can you even ask here that isnt easily googled anyway
in the beginner channel
for me I really just help people even if they can Google it
Then tell them to Google it next time
spoonfeeding sure but they need a head start
Learning to learn also falls under beginner topics I feel. I'm happy to point people to resources or let them know what they can try googling to find what they're looking for.
Often the problem is they haven't developed the knowhow to know what to look for and need a push in the right direction
does saving a dict to JSON not need any extra steps now?
I don't like when the top answer of a forum is just telling others to Google it or linking to another page without elaboration, top searches get rearranged over the years and forums can get deleted.
Speaking from personal experience when messing with Playfab, it got bought over by Microsoft and they deleted the old forums entirely
It's always been serialisable from what I remember?
No, I believe I @ u in a message above a few hours ago showing that newtonsoft can do this
ah ok, sorry it's been a long day my memory is flatlining
Np, was saying it more as a reminder
because you have to recreate an array every time its resized, is an array still the correct thing to use for a list that resizes all the time?
or is there a better way
Why not use a list?
There is a List in c# which handles this for you
a list is just a resizeable array right
It just handles the logic for you, you can treat it as a resizable array
Not as related but if you really want to optimise your list so much you can also look into object pooling
Otherwise, sticking to a list/making your own logic for a resizeable array is just fine
I dont think this is related at all. We dont know what this is a list of, object pooling doesnt apply to everything
Also, if you want to avoid constantly reallocating an array to fit the new size, a List just hides this and doesn't make it any better.
Allocate an array that is big enough for your use case, or consider handling it in batches based on what fits and handle the rest the next round.
This is also why Unity provides the ability to pass arrays into various methods because you allocating it once is a lot better than Unity constantly making one when you call the method
is it possible to make Unity not use GPU at all for rendering and only use CPU?
for context, before i had issues with my nvidia drivers not being detected and Unity was running CPU-only, which was.... bearable but still too slow. i updated and fixed the drivers and they are running well now. now i am trying out an asset (Crest) and i encounter visual glitches, and they might be caused by the drivers being funny. i want to see whether it's the asset or the drivers that are at fault.
so my question is whether I can go back to that CPU-only state without completely turning off the drivers for my entire PC?
i looked it up online and it seems like it's super nonstandard and most forums suggest -nographics which turns off the display of the entire editor but that is not my goal
If you have an Nvidia card, you can open Nvidia Control Panel and assign which GPU to use for which program. I don't know what the AMD & Intel equivalent would be but I'm sure they exist.
This as far as I know is not something you can specify from within Unity.
aha i see, that would make sense, let me try
I don't understand how unsubscribing from events work.
If have I have an arrow function like OnSomethingHappened += () => {DoSomething();};, do I need to unsubscribe? And how would I do that?
I just found out my scene breaks when I reload...I think it's because I haven't unsubbed to any events
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
@sharp bloom its for me
btw, while the inline segmant isn't there. the paste sites can be found in #854851968446365696
What you're doing there is creating an anonymous delegate that then calls your DoSomething function.
What you want to do is something like OnSomethingHappened += DoSomething();, that way you can unsubscribe later on with OnSomethingHappened -= DoSomething();.
Here's a good resource on the topic
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/delegates-with-named-vs-anonymous-methods
yea i was looking for the inline specificly
So if I I understand correctly, if the event is System.Action type, was the anonymous delegate needed at all?
If that in itself is a type of delegate?
{
data.timeElapsed = Mathf.Min(data.timeElapsed, this.elapsedTime);
data.gameTimeElapsed = Mathf.Min(data.gameTimeElapsed, this.gameTime);
if (levelCompleted && data.timeElapsed > this.elapsedTime || data.timeElapsed == 0)
data.levelTimeTracker.Add(id, elapsedTime);
}```how could I rewrite this so I can actually store the least amount of time it takes for a player to complete a level? Right now all I get in my json file is zero
Hey, how could I like... make some kind of event system where I calculate a value and then send a call to see if there is anything extra that would like to modify that value?
Like, imagine a method that makes an attack, so it calculates the damage of it, but the character has an item that goes like "your attacks do magic damage instead"
Like, I cannot really handle that with events can I?
seems like the dict was not even established in the first place
A tool for sharing your source code with the world!
Okay, so I have changed this
ClockScript.OnSecondsChanged += (int context) =>
{
tickTimer += 1;
if (tickTimer >= 20)
{
tickTimer = 0;
EndTurn();
}
};
into this
ClockScript.OnSecondsChanged += TurnEnderEventHandler;
private void TurnEnderEventHandler(int seconds)
{
tickTimer += 1;
if (tickTimer >= 20)
{
tickTimer = 0;
EndTurn();
}
}
private void OnDisable()
{
ClockScript.OnSecondsChanged -= TurnEnderEventHandler;
}
I think now it's getting unsubscribed correctly
Yeah looks correct :)
guys if i wanna change the cupe color in c# i saw someone using cube.getcomponet<Render>
but the vsc aint suggesting it to me
"it" - what isn't it suggesting?
cube is a mesh, your IDE doesn't know what that is. It also can't have a component, they go on GameObjects.
You need to create a GameObject variable, assign the thep to it and then GetComponent will work
Unless of course, you created the var as cube then it's just what halfspacer said
omg thanks <3
Hey, it's been here for a while, can anyone have a look?
Pretty sure that if you are getting how long is taking the player to complete a level it should never be 0. Why are you even checking for 0? The default value should probably be like Mathf.Infinite
Where should I call this?
i think you'd want parens around the ||
Oh nevermind, void OnDisable() of course
perhaps not a fix for the issue, just a sidenote
the idea is when the program is ran for the first time the value is set to 0
should I just make inital value very large to fix this?
The initial value should be infinite, since you are looking for a smaller value to replace it
using 0 is a fine default value imo - a flag for "no value"
{
if (levelCompleted && data.timeElapsed > this.elapsedTime)
data.timeElapsed = this.elapsedTime;
data.gameTimeElapsed = this.gameTime;
data.levelTimeTracker.Add(id, elapsedTime);
}```Yea this seems to make a lot more sense
you're missing braces there
It's fine as a default value, you can work around it, but I prefer infinite here, easier to setup
quick question, when I store the key-value pair into the dict, how would I replace the {id, elapsedTime} with the shorter version?
dictionary[key] = newValue;
[id] = elapsedTime?
do I just replace the last line with this? What happens when there's no inital key-value pairs
You'll need to check for the key first
the entry is created
you don't need to check for setting
ok so just let data.levelTimeTrack[id] = elapsedTime take care of it
noted
i tried this and only going right and jumping seems to work, going left (A key) doesnt do anything for some reason (i went to sleep thats why i responded late)
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
have you tried doing some debugging to check if it's being picked up?
i would but i dont understand the 1f; thing in the if statements, i probably should look it up
could just Debug.Log($"A: {Input.GetKey(KeyCode.A)}, D: {Input.GetKey(KeyCode.D)}");
both inputs are being read
when you only press A?
oh wait you're clamping the speed so it's only ever positive lmao
that would make sense why its not working then lol
what would be a better way to go about with the calculations
i made someone elses code my property to make it and planned to get it working then lookup any details i dont know to slowly increase my knowledge based off things that worked but it seems that i probably should do a little bit of looking up before hand
anybody got the tech support number for this?
it keeps not adding whitespaces, yes i checked the settings
Min speed should be -10
clamp at -maxSpeed, maxSpeed
yea that works but ill do the way chris said since only one variable needed
do I directly get values from a dict by levelTimeTracker.TryGetValue(Id, out var value) given some {Id : value} pair?
do I need to define the type of value being outputted or does it just output whatever the associated value is?
var means the type is inferred. if it weren't inferrable, you wouldn't be allowed to use it there
levelTimeTracker.TryGetValue(Id, out float value) something like that
you can hover over the variable to see what its type is
check in scene view to see if anything is overlapping it and check if the text in the component is correct
it looks fine in scene view. does that potentially narrow it down to the camera?
ok. ty for the response
public class FinishFlag : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
GameManager.Instance.UpdateLevelCompleted(true);
}
}
}``` I attached this script to 3D worldspace UI element but somehow no collision came up
both the player and the flag has a collider, with the flag being trigger
not sure physics and recttransforms will play nice with each other
did the other way around and still didn't work
what other way around?
on trigger enter on the player getting the tag of the falg
If this is just for the flag, you should be using a sprite renderer, not UI.
(Not that it changes the physics)
that doesn't make a difference
it's the physics check that I don't think would work properly
why tho?
anyways, the player has a rigidbody, right?
recttransforms work a bit differently from normal transforms
no, it uses a capsult collider because it moves with a kinematic character controller
ahh
...wait kcc doesn't use rbs?
i thought it did, but i didn't really look into the actual package
I think it's a toggle
I just looked at the panel now that you mentioned it
and there's a rb interaction type
why is your flag a ui element anyways
idk, it's just a visual element in worldspace so I figured just to use ui
nvm it still didn't work
ok adding a rb worked
ok one more question
how do I make sure Timer gets to save the data before TimeDisplay pulls from the JSON file?
also, why is the dict not saved within the JSON?
I checked my files and the dict is just not there
How are you serializing it? Unity json serializer doesn't serialize dictionaries.
There is trick how to serialize dictionaries with lists
you can just use a spriterenderer for that
I thought they did since json has dict support no?
you're introducing some really unneeded complexity
Lists are not dicts.
typo mb
Ight I'll just change it to a sprite
You've yer to show what your Player data serialized part looks like.
oh uhh is it this
Yeah, you can't serialize the dict just like that.
{
//This is to handle how much velocity we want to add to the cube/it's speed
public float speed = 10;
//This is for debugging purposes, making sure everything works fine
public Text textMessage;
//Getting buttons
public GameObject leftButton;
public GameObject rightButton;
//Getting/accessing the script within the button, you just assign the button and it reaches the "HoldButtonHandler" script within it, so you basically don't have to do anything
public HoldButtonHandler leftIsHolding;
public HoldButtonHandler rightIsHolding;
//Getting the cube and it's rigidBody
public GameObject theCube;
Rigidbody2D cubeRigidBody;
private void Awake()
{
//Getting the rigidbody of the cube
cubeRigidBody = theCube.GetComponent<Rigidbody2D>();
//Getting the isHolding variable details for the left button (and the same for the right button)
leftIsHolding = leftButton.GetComponent<HoldButtonHandler>();
rightIsHolding = rightButton.GetComponent<HoldButtonHandler>();
}
void FixedUpdate()
{
if (rightIsHolding.isHolding)
{
int x = 2;
textMessage.text = "You pressed the right button";
cubeRigidBody.velocity = new Vector2(x * speed, cubeRigidBody.velocity.y).normalized;
//cubeRigidBody.AddForce(Vector2.right * velocity, ForceMode2D.Impulse);
}
if (leftIsHolding.isHolding)
{
int x = 2;
textMessage.text = "You pressed the left button";
Vector2 direction = new Vector2(x, cubeRigidBody.velocity.y).normalized;
cubeRigidBody.velocity = direction * -speed;
//cubeRigidBody.AddForce(Vector2.left * velocity, ForceMode2D.Impulse);
}
}
}
I am confused at the last part, when I do cubeRigidBody.velocity = direction * -speed; the player moves faster compared to x * speed
Can anyone explain please?
This is a player movement script
I understand 90% of my code only, the rest doesn't make much sense to me either due to shit tutorials
there is trick but not shure it will work fine for your case https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
I'm not totally sure what serialization is to begin with :d
that one isn't for you
They weren't talking to you
In the right side check, you multiply by speed prior to normalization. In the left side check, you normalize and then multiply by speed
what scenarios are you comparing, exactly?
@open apex you normalizing vector after speed was aplied your actual speed is changing vector direction instead of affecting actual speed
thanks lemme read into it
I don't undestand what you mean.But here is an explanation, basically I am trying to add player movement to my character, I have decided to use velocity and to adjust how fast the player moves I have given it a variable called speed. What I did was "cubeRigidBody.velocity = new Vector2(x * speed, cubeRigidBody.velocity.y).normalized;" no matter how high "speed" was the cube wouldn't move faster, so I looked up at a tutorial, they did " Vector2 direction = new Vector2(x, cubeRigidBody.velocity.y).normalized;
cubeRigidBody.velocity = direction * speed;"
instead it start to move just fine but I don't understand how, is as foo mentioned because it was normalized? If I remember correctly when normalized the max value of the variable would 1 or -1 (?)
normalization of a vector makes its magnitude 1
for a vector2, that means sqrt(x*x + y*y) = 1
Owhhh
You need rb.velocity = direction.normalize*speed where direction is Vector2
if this is supposed to be a sidescroller context with gravity, then you don't need to normalize the vector at all, since that'd be affecting gravity
I am not exactly sure why I would need to normalize it either as it's just 1 and -1, I just do it because it's "good practice"
you don't need to normalize in this scenario
in this context, normalization would be done to turn some x/y values into a direction, with magnitude 1
in a top-down game, if you press W and D and turn that into a vector, that would be (1, 1), which is actually going faster than going only right or going only up, so normalization would make the magnitude, and thus overall speed, uniform
but your code seems to indicate you're in a sidescroller, so you don't need anything like that
it's not w and d it's buttons
UI
i'm giving an example
wow 😐
Ohh ok
@open apex Normilzed make vector Magnitude equal to 1 not X and not Y the lenght of vector so if u want ur player move with speed 5 you normalize the vector coz in else case vector magnitude can have length 10 or .3 and speed will not be 5
damn use some punctuation 💀
Hunter is a proper pc user
but I understand what he means
Its useful for many things e.g. get direction from a to b, normalise and then scale to new desired length with ease
how would I go about detecting if the character is on the ground (2d, im using capsule collider 2d and rigidbody 2d on the player)
I love programming, I've got very little to no idea what I'm doing and I'm going of based off of theory and a bit knowledge, if something doesn't work = research, if it does = understand how it works and keep on moving
(cause rn there are infinite jumps, even in the air)
there's quite a few ways, try googling it
I was wondering if anyone was free to help me with something? I'm having issues getting collision to work, it's supposed to hit something with the tag "Power Up" and then destroy itself but it's not recognising it and won't hit it. I have a collider and Rigidbodys on both objects.
Did you set the tag of target?
Yes
have you tried debugging to see if the message is being called
Set the Debug.Log(collision.gameObject.name) and check if it works
also, is the powerup a trigger?
I have but not in the way set out above, I'll give that ago and report back.
Yes
then there wouldn't be a collision
use the trigger message
make sure to update the parameter type as well, they have different signatures
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public int bulletSpeed = 5;
private float bulletRange = 10.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(new Vector3(0, 1, 0) *bulletSpeed * Time.deltaTime);
if (transform.position.z > bulletRange)
{
GameObject.Destroy(gameObject);
}
}
private void OnTriggerEnter(Collider other)
{
if (CompareTag("Power Up"))
{
Destroy(gameObject);
Debug.Log("Hit");
}
}
}```
I am using OnTriggerEnter
CompareTag there would be checking the tag of the current GO
"bullet" doesn't seem like it'd be the same object as the powerup, so you probably want to check the tag of other
What I tend to do is check if the player is colliding with the ground or not that then makes a isGrounded variable to true, then ensure that in the if statement that you test for a key press add the isGrounded variable as well.
i tried to do that but it said something like the isGrounded thing wasnt valid
use this instead CompareTag is doing nothing ````if(other.tag=="Power Up")```
also are tags for colliders gonna be useful to differentiate like a wall from the ground, so i cant just wall bounce alot
you can use the CompareTag just fine, doesn't need to be a tag comparison - just needs to be on other
Works like a charm, so other just takes what it's hitting and checks it's tag?
yeah, you were checking the current GO before as i mentioned
That makes sense, Thank you!
You need to do other.gameObject.CompareTag("Power Up")
what was the error you got
unsure cause it was a while ago that i tried
no you don't, CompareTag is a method on Component as well
you don't need the intermediate .gameObject
ah thought you were just trying it
What do you mean it cannot work such way it is not possible CompareTag("Power Up") this code is 100% uncorrect
didn't say it was
Alternatively you can shoot a raycast at your feet and if it hits something then you're grounded
other.CompareTag("Power Up") and other.tag == "Power Up" are both fine
.gameObject is unnecessary
I didn't remember if collider have field tag so used gameObject to be sure it will works
you are right there
CompareTag() is better to avoid a string allocation
only with a taghandle, no?
Hm? CompareTag() doesnt need to allocate the tag string in managed memory for the comparison.
Should be why CompareTag() even exists
anyway bit much to think about for beginners
could you elaborate? is this something about the comparetag using extern'd methods?
(im curious about the internals of what was done there)
Yea, this just passes the managed object to a native function to perform the comparison so we avoid allocation.
the tag property however needs to produce a string in managed code for comparison to then be done with string == string
ah, cool
(checking my understanding) so it's not the == vsCompareTag that's optimized, it's the removal of .tag that's better?
Yea, string comparison is done either way but one is a tad better.
And ofc TagHandle exists to further improve things
I looked up how and got it working with this, is there any optimisations i should make or should this be fine?
im thinking i could do the 2 ifs in a if and elseif based on diff languages ive used but idk if thatll be true for this
fyi, see below !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you could just do _Grounded = hit; though
for savedata to check data, do I need to load it first?
{
data.levelTimeTracker.TryGetValue(SceneManager.GetActiveScene().name, out elapsedTime);
}
public void SaveData(ref PlayerData data)
{
if (GameManager.Instance.levelCompleted && data.timeElapsed > this.elapsedTime)
{
data.timeElapsed = this.elapsedTime;
data.gameTimeElapsed = this.gameTime;
data.sceneID = SceneManager.GetActiveScene().name;
if (data.levelTimeTracker.ContainsKey(SceneManager.GetActiveScene().name))
{
data.levelTimeTracker.Remove(SceneManager.GetActiveScene().name);
}
data.levelTimeTracker.Add(SceneManager.GetActiveScene().name, elapsedTime);
}
}```
@eager scarab optimization looks fine
I am afraid I am also a newbie so don't know much about optimization but that is what I did when I had the issue :)
you don't need the ifs (in case you missed my message)
yeah im newbie-er, started yesterday and barely did anything since lol
_Grounded = hit.collider != null; would also work
also fyi for the future, else exists
what do you mean by "check" exactly?
idk why i didnt try this before since thats exactly what it is in other languages lol
yeah pretty much every language uses if and else
thanks, didnt know hit was already a boolean
the differences are in else if vs elif vs elsif, and then/fi/end
it isn't, it has an implicit boolean conversion - it can be treated as if it were a boolean
// Implicitly convert a hit to a boolean based upon whether a collider reference exists or not.
public static implicit operator bool(RaycastHit2D hit)
{
return hit.collider != null;
}
comparing between data.timeElapsed and this.elapsedTime
But I have a bigger problem here apperently
there's no saving values
I've serialized the dict properly now but it seems like I can't save my data
what is the best way to add dialog system to my 2d unity game? i saw tons of video with different ways which one is your fav?
INK
well yeah you never actually told it to save it anywhere
buy an asset 😄
there's no "best", in general
Ink is a good system and is free
Comes with its own markup you can easily interact mid dialaugue and branches
i dont try yet but ink was the system i like
wdym? Isn't if (data.levelTimeTracker.ContainsKey(SceneManager.GetActiveScene().name)) { data.levelTimeTracker.Remove(SceneManager.GetActiveScene().name); } data.levelTimeTracker.Add(SceneManager.GetActiveScene().name, elapsedTime); saving the data?
I used it a couple of times its real good for a free system tbh , depends how complex you need
it's saving to PlayerData, but it's not actually statically saving anywhere else? (to network/to disk)
what is your save system?
you're leaving a lot to be assumed
i am looking for basic one because i kinda overwhelm with other tutorials so far basic dialogs and little bit choice answer is enough
https://www.youtube.com/watch?v=aUi9aijvpgs I'm following this tutorial but to paraphrase it it's saving to a data persistence manager, where the singleton saves a snapshot of the data to store it in json
In this video, I show how to make a Save and Load system in Unity that will work for any type of game. We'll save the data to a file in both a JSON format as well as an encrypted format which we'll be able to toggle between in the Unity inspector.
IMPORTANT: For WebGL games, because WebGL can't save directly to a file system, a different meth...
define " basic " building your own will be a lot more work than quickly adopting already fleshed out system , granted there is an initial learning curve but it's real easy imo. Ofc you can do your own with scriptable objects and arrays etc. I think unity has a demo for that with thr Chop chop demo
good idea i was totally forget to look unity's own tutorials
A tool for sharing your source code with the world!
sure take a look at them. The most basic string[] dialogues lol
Nothing there saves to a json. (I missed the tabs) It just adds data to a dictionary(?)
IIRC, dictionaries can't be serialized in a json, Chris?
I missed a script, I have
using UnityEngine;
[System.Serializable]
public class SerializableDictionary<Tkey, Tvalue> : Dictionary<Tkey, Tvalue>, ISerializationCallbackReceiver
{
[SerializeField] private List<Tkey> keys = new List<Tkey>();
[SerializeField] private List<Tvalue> values = new List<Tvalue>();
public void OnBeforeSerialize()
{
keys.Clear();
values.Clear();
foreach (KeyValuePair<Tkey, Tvalue> pair in this)
{
keys.Add(pair.Key);
values.Add(pair.Value);
}
}
public void OnAfterDeserialize()
{
this.Clear();
if(keys.Count != values.Count)
{
Debug.LogError("Deserialization error, key-value mismatch.\nKey : Value " + keys.Count + " : " + values.Count);
}
for(int i = 0; i < keys.Count; i++)
{
this.Add(keys[i], values[i]);
}
}
}```
it has the initial values of the playerdata but not any updates
Guys, any advice on how to make Transform.Translate get the Vector3 once, and move in that direction, even if the direction changes?
I can't see where DataPersistenceManager.Instance.SaveLevel() is called
idk anything about using json in c#
get the Vector3 once
what do you mean by this?
wdym get the Vector3 once? which vector3 are you talking about ?
Vector3 never changes, eg Vector3.right will always go in the same direction no matter rotation etc.
if you want to apply a translation that doesn't care about the rotation, you can set Space.World or add to the position directly
I figured it out 🙂
didnt really see any of the context but it can using newtonsoft
https://www.newtonsoft.com/json/help/html/serializedictionary.htm
newtonsoft > JsonUtility
not that it's a direct solution but might even just be worth turning that dict into a serializable struct or something in the event you want more data in there too
in some situations maybe "overkill" but if your making a whole save thing anyway
one thing newtonsoft has weird issue with Vector3. not sure if thats still a thing but you have to disable "self-referencing loops " or whatever the option was
what, for like normalized or something?
There is another package with custom converters for unity, handling most of the unity types at least
yea
but you just add cs JsonSerializerSettings settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; I think and it goes away
{
if (GameManager.Instance.levelCompleted)
{
SaveLevel();
}
}``` (within the singleton)
why would it serialize properties rather than their backing fields 
how long does it take me to rewrite this in newtonsoft?
No Idea tbh I just learned the hard way I had to do that.. also you cannot disable it on Unity Cloud so you are stuck making custom Position/Vector3 of your own basically almost a ORM
unity cloud strikes again
its the same thing. except the method changes from
JstonUtility.toJson vs JsonConvert.SerializeObject
ima check this out thanks! this only works for local anyway right ?
I'm stuck making custom structs for UnityCloud Save because thats server side and I cannot change anything newtonsoft
I'm not sure about this whole cloud aspect of it or what you can or can't do there tbh
Could be valuable even just seeing how they handle it in the package I linked, if that helps for your case
anyways I don't think I have time to experiment, could someone tell me why does this not update my data?
basically you save
var playerData = new Dictionary<string, object>{
{"firstKeyName", "a text value"},
{"secondKeyName", 123}
};
await CloudSaveService.Instance.Data.Player.SaveAsync(playerData);```
But if you pass a serialized object in `object` like a struct that contains Vector3. you get the same error i mentioned earlier about newtonsoft self-referencing loop thing but you cannot change anything since its on unitys server side of things
I just ended up making my custom `Position`(3floats) like vector3 anyway but still
I have a Vector3 to Position converter and vice versa
which part SaveLevel ?
why on earth did i think the basic value types weren't object's. thank you for accidentally enlightening me
A tool for sharing your source code with the world!
revelations!
but yeah sometimes I still don't know if I should just use object or I'm better off using a T generic, always use generics cause iirc with object there is some boxing that needs to happen? I'm no expert in this though so not sure
Yeah I always get worried about direct generics not doing serialization related stuff well since unity object classes dont like it
without defining them in a inheriting type
i have a generic INetworkSerializable struct i still gotta test
Oh that I did not know lol TIL
well they aren't in java/js for example so it's not an unreasonable assumption
so its not saving ? sorry I just got here
object class is created by Microsoft for Companies to ask about it on the Interview )
yea, the JSON file only have the presets
what else it supposed to have?
well, changes to values in playerdata
you logged the values before it being serialized in a file ?
how so?
and also, how can I fix this?
Debug.Log
You are able to fix it if you narrow down to the cause
ok I do have a key-value pair
I just could not call it
not sure what you mean by that
on my display script
basically I did save data in the json
but I couldn't call it
recalling the serialized values of PlayerData that is stored into the JSON to a script
loading?
this could be worth doing?
So the save values are correctly saved in the json file ?
so which part isn't working lol
When you log best time what value do you get?
does updatetext run after loaddata
I got 14 seconds in the JSON file
so it should show
im not sure about this
it needs to 😛
i know that its more like idk how execution order works in this case since LoadData is called by the singleton
nope
Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
so got this vector3 from the A* pathfinding algorithm. I already have a way to smoothly rotate my 2d gameobject towards the vector using slerp, but i also have a mesh that i wish to rotate towards this direction. plugging in my transform directly doesn't work as it simply flips left and right instead of actually rotating.
simpily put, i want to rotate towards this vector3, but gradually instead of all at once. any tips?
depends on how you want to do it
does it move to one point to the other with a fixed speed or a fixed duration
normally most would just use something like Vector3.MoveTowards to push the transform in a direction per frame with a max amount it can move per frame
fixed speed
then you can add other concepts as needed like how long it takes to accelerate and deaccelerate
i want my player to be able to spawn in a random position (2d platformer side scroller).
whats the most optimal way to get a random position within a certain distance of the players death location that the player can safely spawn in (meaning head or toes wont be inside any objects with the layer ground).
if there is a tutorial that touches on this mechanic specifically, please let me know
i already have the movement and stuff set, i just need to rotate a seperate mesh towards the vector3
so the variable needs to remain a vector3, no quaternion conversion
you can just convert the vector3 to quaternion with LookRotation as needed though
get the Quaternion.LookRotation of your directinal vector, then you can use Quaternion.RotateTowards feeding in the objects current rotation, and the LookRotation and a max degrees update
i just wanna check is this the right channel to ask for help?
read the channel title
ah sorry i dont really go in servers thank you tho
ive been struggling with finding the right resources and i dont know where i should really look for learning unity, could someone point me in the right direction?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you for the guidance ill be sure to check all this out
they still haven´t fixed the learn pages for germany. it´s still down
Hello guys, first time here!
Trying to instantiate a GameObject @ a certain time rate, but it keeps instantiating at every frame even after the timer resets
void Update()
{
Timer = Time.time;
if (Timer >= SpawnRate)
{
SpawnBalloon();
}
MoveSpawn();
}
void SpawnBalloon()
{
Timer = SpawnRate - SpawnRate;
Instantiate(Balloon, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
}
They're doing that inside SpawnBalloon, the issue is how they are tracking time though as just setting it to 0 won't work
not Timer = Time.Time it is not correct
{
Timer += Time.deltaTime;
if (Timer >= SpawnRate)
{
SpawnBalloon();
}
MoveSpawn();
}
void SpawnBalloon()
{
Timer = 0;
Instantiate(Balloon, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
}```
im confused, how is void wrong in void FixedUpdate()
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public Rigidbody rb;
public float moveSpeed;
private Vector2 _moveDirection;
public InputActionReference
void FixedUpdate()
{
rb.linearVelocity = new Vector2(_moveDirection.x * moveSpeed, _moveDirection.y * moveSpeed);
}
}```
You're missing a ; and a field name after InputActionReference
Thanks @valid violet , that solved it!
It does
Hi guys! I was watching a tutorial of Unity Input System in Unity 6, and when they use MovePosition in rigidbody, they multiply it with Time.deltaTime, but the logic is implemented in FixedUpdate. Why not use Update instead? I guess cause it's physics related, but why use deltaTime then?
Member declaration, the member being public InputActionReference, followed by invalid void which shouldn't be there, that's why void is underlined
because you didn't finish the previously line it thinks you are trying to finish it there but void is a reserved keyword so it is not valid in that previous line
Also, the vector2 values of move action are in update, so could this cause inconsistencies if there's frame drops?
i think it doesnt make any difference to use deltatime inside FixedUpdate
deltatime and fixeddeltaTime is what i am saying
I've read that it can be cause the fixed updated rate could be modified over time, but a part from that, idk why they use it then
MovePosition as the name says is using the rb position, that is why you need to use it
Hmm okay, so I can use FixedUpdate for MovePosition without worrying about using deltatime or fixeddeltaTime ?
you have to use deltaTime, in short
And for reading the values of vector2 in Move action, it's okay to keep it in update or better to set it in fixed update too?
it is unclear what you are asking. do you have the code
Ooooh okay, so what you're saying is I can use both the times (fixed and normal delta times)
Sure, I can send you the unity tutorial link too if you want
This method is called inside FixedUpdate
yeah looks ok from here
Sure, but sorry if I didn't make myself clear. Why do I need to use a Time variable (deltatime and fixeddeltaTime)?
I thought that fixedupdate was enough to not depend on framerates
fixedUpdate is run independently from the framerate yes, but if you later change the physics framerate from the default of 50, maybe even runtime by script, it won't be independent
good questions actually, FixedUpdate runs 50 calls per second as we know, so why the deltatime
You also generally want to work with some clearly defined units, like acceleration of m/s^2, you may not get any of that if the physics timestep (Time.fixedDeltatime) is not factored in correctly
Okay, and if I change the framerate from 50 to 25, Time.fixedDeltatime also changes?
Yes, it gives the time between physics frames. In case of 50 it would be 0.02, for 25 it would be 0.04
Thanks! Now I got it
Btw, in fixedUpdate, it doesn't really matter whether you use Time.deltaTime or Time.fixedDeltaTime, because deltaTime is identical to fixedDeltaTime during fixedUpdate. It is good practise to prefer fixedDeltaTime though to indicate that you are working with physics timesteps
Also, this m_moveAmt will be dependant on normal frame rate if called in update right? Or it has nothing to do with it
Shouldn't have anything to do with it. AddForceAtPosition increments Rigidbody.GetAccumulatedForce (well not the getter of course) which then will get applied during the next physics update. AddForceAtPosition doesn't take Time.deltaTime into account in any way as far as I know, it just applies the given impulse (in the impulse ForceMode) to the counter (accumulatedForce). Don't know how much sense that makes to you. What is important though is that you do ForceMode.Impulse as you do, if you used something like ForceMode.Force, you would get different jump heights if you changed the physics time step (your regular framerate wouldn't matter still). ForceMode.Force expects you to apply that force continuously in every frame, Impulse you can apply only once.
np
guys can someone help me with some tutorials/pathways from learn.unity.com? some are good? i have a best/good knowledge in coding but not in unity, in c/c++ but i need to learn unity for a project. i did Unity Essentials and Junior Programmer and i want to start rn VR Development from learn.unity.com/pathways but i don t feel like i improved a lot, if someone know some tutorials/courses from learn.unity.com? in this ideea. i need to learn unity/VR
Nothing, I google it and I found it, sorry & thanks!
Just keep working on projects eventually you will gain more experience
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
guys take a look at this code snippet
https://paste.mod.gg/ntklmoluocoa/0
I have an object with x rotation -10 degrees and I want it to go to 40 degrees it does exactly that BUT for some reason the rotation the gets reversed and it comes back up. I dont want that to happen anyone know any solutions?
A tool for sharing your source code with the world!
this code wouldn't do that last part
you'd have to show more code
Here it is https://paste.mod.gg/xwjigquavjbw/0
A tool for sharing your source code with the world!
you should share the full script
Need help rotating an object while it is moving via Transform.Translate
Tried LookAt and RotateTowards and a couple of other methods but in the end the result was - that the model of the object was not rotating.
The only thing rotating were Vectors and directions of X and Z Coordinates
(What I'm trying to do is - create a projectile of a straight line and make it look directly at the player while flying)
Transform.Translate will not affect the object's rotation (though it may be affected by it) so your question doesn't make sense
the full script is like 300 lines is it ok if I share just that function??