#💻┃code-beginner
1 messages · Page 730 of 1
Then also notice that HingeJoint is a thing you can put on an object in the inspector
if script is on gameobject its a component, simple as that
and you didn't think to.. yknow, add a rigidbody?
firstly, Id assume the tutorial telling me in detail how to do the thing would tell me to add a rigidbody, and secondly, even when I did, it still failed to bring results
"script" is kinda nebulous. the closest actual definition would be that a script is just a file with code.
so.. a script can be a component if you decide it means that. but if you're hung up on the definitions, it's best not to use "script"
so a script isn't a Compoent at all, so would my line of code thoretically never work for what Im trying to do?
What makes you think a script is not a component
I feel like my screenshot shows precisely the opposite
Those boxes on an object in the inspector are components
it's not that "a script isn't a Compoent at all", it's that a script is only a component if you are referring to a class that inherits from Component (like every MonoBehaviour you create)
if a script contains something that isn't a monobehaviour, then it isn't a component
the scripts are files, and they can have component definitions (a class extending MonoBehaviour, which extends Component) inside. when you add the "script" onto a gameobject, it creates a component corresponding to the component definition.
I know Im being difficult here, and sorry I am, Im just genuinely confused on this, but I don't think I see a script in the red? I guess its technically the same thing as everything else?
Everything that looks like that is a component
the point was to show that those things are components
ok thank you
the boxes on an object
so I would be looking to add Camera_Move, not the object as a component then?
If you are trying to get a component named Camera_Move, then that is the component that you would get
Thank you
actually, every single prefab that the essentials pathway provides already has a rigidbody. i checked both versions.
Maybe I added it in wrong? maybe I added in the raw model instead of the prefab?
that seems.. hard to accidentally do
so to get one step further, it'd be something like this (not correct but closer)
they're all in a folder called "prefabs" then "characters"
you should just go do the programmer essentials.
GetComponent is taught there.
I do wanna also note, when someone mentioned it in the first place, they said I might be on the wrong version?
that was me, and it was in reference to using a newer version where the API had changed, and not in reference to you doing something wrong (which seems to be the case here)
Do you understand that variables have types. They define what kind of thing that variable can hold
int x is a variable named x that is of type int. You can set x to any integer.
I know float and bool off the top of my head
GameObject Room is a variable named Room of type GameObject. You can set Room to any GameObject.
If you're trying to get a Camera_Move component, why are you trying to store it in a variable that holds GameObjects
I see what you mean
knowing the names of two types is not the same as understanding what types are. you should consider stopping what you are doing and going through some beginner c# courses, like the ones pinned in this channel.
just noting that I know what they are, if Im not wrong (I might be) bools are for direct full numbers, I know for a fact that floats are for (not only full numbers) but fractions of numbers, like 1.6 or 0.7?
you're 100% wrong about booleans
You can check these things
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/bool
Oh yeah I totally forgot that it was like that
just haven't been using Bools recently
ehh i kinda feel the "everything" there is misleading
public is not a type, that kind of thing
So am I looking for a float, something similar to this? ``` float Room = CameraTrigger.GetComponent<Camera_Move>();
Please stop
and think
and read the things I've said
Why
would you store
a value of type Camera_Move
in a variable
that holds floats
What is the point of asking questions if you won't read the fucking answers
Im trying to understand this Im just very confused, Im sorry
stumbling around for 2 hours because you don't understand types is not a good use of time
go learn for 20 minutes and then solve the issue in 2 minutes once you actually understand the things you're writing
walk before you run.
learn the basics first. you're skipping over them right now.
GetComponent<Chungas>() will get you a value of type Chungas
Which you can store in a variable that can hold a value of Chungas
If you want to store the value of GetComponent<Chungas>()
you would make a variable
of type Chungas
Do you notice
how these are the same word
on both sides of the line
that is not an accident
that is, in fact, how things work
(give me a second my desktop is kinda chunking around rn because Im loading a lot rn* and a quick brb)
I feel like Im starting to get it but is it ok to ask some questions, again, sorry if Im asking a lot of dumb questions Ive been very confused
perhaps learning c# properly would help instead of stumbling every 5 seconds
also, hes still looking for help on thios one*
Ive been trying to learn as I go after other tutorials like the essentials pathway didn't work for me, I do wanna double check if I did something wrong in the essentials pathway or if its just not working
you did something wrong
the essentials pathway is set up fine, you did something wrong
yeah I did something wrong
I went to models Characters instead of prefabs characters
yeah you can see here actually. you did indeed put in the model. the tutorial said to use the prefabs. which are in the folder named Prefabs
the problem is learning unity isn't going to teach you how to program with an object oriented language like c#
if the programming part is hard you should just learn that in isolation
some tutorials and such may teach unity parts and describe some things but it wont tell you what generics do properly
Ive been slowly warming up to programming, using both Gamemakers scripting and Godot to make basic tests, Im just having growing pains with C#/Unity (esp cus I have a learning disability)
there is also the fact that you don't need GetComponent in this situation anyways
you can just type Camera_Move as the thing you want to get
(but you'll still have to learn how to use GetComponent properly eventually)
yeah honestly I should have asked if there was global varables, I only asked about GetComponent because from everything Ive seen it was the most proper way to do the next step in my test project
thats a good start! scripting langs like gdscript are more relaxed and help you learn but c# is a step up so keep up the learning and practice
c# doesn't have globals, no
I made some pretty good stuff in GDscript, but the game I was making was too complicated for myself. still happy with myself though
the point of a tutorial is to teach a specific thing in isolation, to see how that one specific thing works.
when you skip tutorials, you end up having to figure out everything all at once before it can work.
that's your current issue
I actually thought I was doing pretty fine up until then, even if it took me a long time for some basic stuff like refrencing other gameobjects in scripts to make trigger areas I thought I was doing fine
it wouldve taken you less if you took a break to actually learn them properly rather than trial & error
tbf I had already assumed that Unity Essentials was broken based off what I already asked and was told in another server.
it wasn't when i did it and i don't think anything changed
what did change was unity 6.1 changing the default input handler
well, as far as Im into it, it was because I didn't go to prefab 😓
go redo it with that new knowledge
i'm having collider issues
is anyone here able to help?
i think i posted something about it earlier but you guys were busy so it's no fuss
here
make sure layer interaction and their layers are set up appropriately.
the collision/trigger message will be sent to any components that are on the same gameobject as the collider, and a rigidbody if one is present, so, do you have a rigidbody?
mainly you'd want to distinguish the messages from each collider, here are some options
- consider if it'd make sense for one of them to be a trigger
- use separate scripts on each collider's gameobject (and rely on other objects' rigidbodies for collision)
- check the thing you're colliding with in the message handler
If an object has multiple colliders, it basically melds them all into one. If you want different behaviors for different colliders they need to be on separate objects
Consider making one of them a child object
isn't one of them already a child
this is just a demonstration of some of the issues related to it
the child object is the trigger with the larger collider
yes
is one of them a trigger and the other non-trigger?
then your messages should already be distinguishable
it's saying this here
that would make sense with the NREs too
that's the stacktrace. it's where the issue is from, it's not what the issue is
i think i already put it in the child object to ignore surface collisions
!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.
show SlingerCoinScript with one of the large codeblock things
you can just ask me for the code :)
for your convenience lol ¯_(ツ)_/¯
i wouldve said like, "show !code" before but the new bot doesn't support that yet, it turned into this
alright i can't share the whole thing, should i just share the collision handling parts
wdym you can't share the whole thing
i said to use the large codeblock part
-# the bot command was necessary after all...
check your bio...? for the advertisement? 
paste.ofcode.org doesnt work for me btw
i just clicked the first one in line
should i download it as a text file and post it here or am i supposed to do something else with it
click save then copy the url
A tool for sharing your source code with the world!
whats the error
i don't know
aside from the trigger/collider mixup thing which isn't completely gamebreaking, when a coin is hit against a wall and destroyed and i shoot another one, i get an error
there should be a red sign in the unity console
now check the exception stack...
it even says what to do
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.GameObject.GetComponentInChildren (System.Type type, System.Boolean includeInactive) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.GameObject.GetComponentInChildren[T] (System.Boolean includeInactive) (at <b6ea36b6733e4deea99187f144c6addc>:0)
UnityEngine.GameObject.GetComponentInChildren[T] () (at <b6ea36b6733e4deea99187f144c6addc>:0)
SlingerCoinScript.RedirectCoin (UnityEngine.GameObject otherProjectile) (at Assets/Scripts/SlingerCoinScript.cs:52)
SlingerCoinScript.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/SlingerCoinScript.cs:32)
oh it doesn't format very well as a message
does it?
slingercoinscript line 32
we can read it fine, but did you read it
yeah
i looked at line 32 and 52 of slingercoinscript
i commented line 32 to see if it was the issue but nothing changed, i'll look at line 52 now
look at line 32 then read the red error again
which is a single squiggly bracket
so maybe that's a clue as to why it's happening
you aren't updating slingerScript.activeCoins when they're destroyed
or at least not properly
public class CoinProj : ProjectileProperties
{
public GameObject coinOwner;
public SlingerCoinScript childScr;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Surface"))
{
if (other.contacts[0].normal.y < 0.01f)
{
Debug.Log("Coin destroyed on surface");
childScr.slingerScript.activeCoins.Remove(gameObject);
Destroy(gameObject);
}
}
}
}```
this is the code that makes the coin break against surfaces
it should be updating the list when it hits a surface before destroying itself
i'm looking through it all now and it's either the fact that it's 11pm or my lack of experience but i'm stumped
according to the error, you are trying to access something that's already been destroyed
yes, i am trying to look for it
that thing should be on line 32
Hoping anyone can help me with rotation math. I'm trying to find the angle between the mouse and player, and rotate the player. It seems to work when the player is at the bottom, but it breaks when the player moves.
private void Rotate()
{
Vector3 mousePos = Input.mousePosition;
angleRad = Mathf.Atan2(mousePos.y - transform.position.y, mousePos.x - transform.position.x);
angleDeg = (180 / Mathf.PI) * angleRad;
transform.rotation = Quaternion.Euler(0f, 0f, angleDeg);
}
alright. i looked at the layer inclusions/exclusions for my projectile and coin, tweaked a few things and now i think it's working somewhat
that solved everything ._.
nice
all i had to do was change the collision rules for the bullet and projectile.
i didn't have to look through my scripts at all
thanks for putting up with me i guess
so i made a character prefab using a Scriptable Object to keep track of important vars and call events
i was just instantiating SO at runtime and i thought everything will be fine
but now im realizing i cant change any single value for a given character!
because the instantiated SO doesn't exist while the game is not launched
what do i do? 😵
what are you trying to do exactly
im trying to make a universal agent that can act like a player, npc, enemy
so i can drop it, change a couple vars and it becomes whatever i need
in other words the problem is prefabs dont create their own permanent scriptable objects when you place them, and instead reference the main one (till you run them and tell to instantiate the SO)
Is anyone able to help me debug a unity script? Im taking an intro to Programming class and cannot figure it out
First, can you shoot backwards?
I think you should try having a general SO, and then more specialised SOs like player, enemy etc that inherit from it
Is that an intended behavior
!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.
what are you trying to do
If anyone is able to take a look, this is my script. My issue is that I am trying to make a collectable block as I go along an infinitely spawning track and upon collecting this block a new one will spawn. However, when I collect this block, blocks rapidly spawn as long as I am inside the block and instead of the blocks continuing to spawn ahead of the user they all spawn in the starting position
if I sit long enough in the block itll spawn like 10k blocks and crash the client
long enough being like 5 seconds lmao
code is too long, use one of the paste sites
so a bit like temple run? you collect a block and then a new one should spawn further ahead
well thats probably a good idea in general, but my question is what if i want to change speed for one guy for example
how do i do it? if the SO instance is created in runtime?
is SOs generally not the practice for this?
also you can probably just use a boolean flag that you check so the block spawning only triggers once
@robust mural yes exactly like temple run
you can just change it in the specialised SO
does this work: https://paste.myst.rs/sft65hzw
a powerful website for storing and sharing text and code snippets. completely free and open source.
add a boolean that you change the first time the check says you're in the block position so it only spawns one block
so like.. manually copy them?
what
you can pass in a unity object as reference in instansiate if you ever want to duplicate them eg.
myRuntimeSo = ScriptableObject.Instansiate(myAssetSo)
@fast whale ok i’ll try this in a bit, driving home from school now. Would this also fix the blocks all spawning in the same location? because currently it just puts them all on the starting position
that's probably related to how you determined the position for the new cube, probably the Vector3, but can't say for sure without knowing more specifics
well thats what i use
agentData = Instantiate(TemplateAgentData);
my problem is that you cant edit these i dont think, this isnt stored while the game is not running
you can edit templateagentdata
if its per instance you'd want it on a monobehaviour on said instance or a base class that exists on a monobehaviour
Testing that actually helped a lot. It looks like the point of rotation is the bottom left of the viewport (Which isn't (0, 0, 0))
mouse position is wrong?
i see.. so cant go pure SOs then
thank you
Maybe if you put the point of rotation on the middle of the cube
The code I used is:
private void Rotate()
{
Vector3 mousePos = Input.mousePosition - transform.position;
angleRad = Mathf.Atan2(mousePos.y - transform.position.y, mousePos.x - transform.position.x);
angleDeg = (180 / Mathf.PI) * angleRad;
transform.rotation = Quaternion.Euler(0f, 0f, angleDeg);
}
I thought that subtracting the mouse position from the player position would make it the center. What can I change to make the player the centerpoint?
try Camera.main.ScreenToWorldPoint(mousePosition)
to translate mouse position into world space
I had that initially, but that makes it not rotate at all with the mouse
The game is 2d tho right. so you would only care about the x and y position
or maybe try to normalize the vector
Yeah, but since I'm using 3D objects it needs to rotate on the Z axis to move up and down, right?
what happens if you do mousePos = INput.mousePosition - transform.position + 10;
where is the rotation then
The last Line is transform.rotation = Quaternion.Euler(0f, 0f, angleDeg);
I do wanna ask a small question, why would I ever make a custom variable private instead of public?
because if it doesnt need to be modified from outside class it should remain default private
you may end up modifying it later on in the future , or someone else and break something
Similar reasons as to hanging up your laundry when you're done with it instead of just leaving it in a large pile on the floor
If you aren't supposed to edit it from outside the class, might as well make it so it can't be
then you won't have to sift through a bunch of things in your autocomplete that might break the game if you pick the wrong one
So if I have 3 public Vars that I want to change, would that cause issues or is it just harder?
(I gtg, I'll read any follow ups when Im back, ty)
Do you need to edit them from another class?
It's essentially just good writing. Making a variable private or public doesn't do anything to the actual variable. HOWEVER, you make a variable private if it's not supposed to be edited in another class.
Let's say you have a variable X that is essential for the class X to work.
Let's say you used variable X in another class and it's not private. You accidentally edit the variable. Now class X doesn't work.
Now, if you had a long line of code, the trouble shooting would be a nightmare.
if it was private, you wouldn't be able to access variable X in the other class. only in class X
you will prevent accidental bugs by keeping them private when they don't have to be public
I see I see, tysm
So, I'm doing the unity pathway and one of the challenges is
Bonus: The game can go on forever
• Add a “Time: __” display that counts down from 60 in whole numbers (i.e. 59, 58, 57, etc) and triggers the game over sequence when it reaches 0.
The hint says
Hint - Google, “Unity Count down timer C#”. It will involve subtracting “Time.deltaTime” and using the Mathf.Round() method to display only whole numbers.
I decided to just do what I know instead. It seems to work, but tell me how stupid it is.
IEnumerator Countdown()
{
while (isGameActive)
{
yield return new WaitForSeconds(1.0f);
UpdateTime();
if (time == 0)
{
GameOver();
}
}
}
public void UpdateTime()
{
time -= 1;
timerText.text = "Time: " + time;
}```
You should really learn how to use DeltaTime to track time, it's a very important skill
Looks like a lot of people used coroutines to make the timer for this challenge, I can see them all talking about it in the comments section
It does work, but it's a lot more overhead and you're denying yourself the purpose of the task which is to actually gett an intuitive sense for what deltaTime means
What's the value of Time.deltaTime? One of the forums has timeLeft -= Time.deltaTime as a solution
Well, the timer is working, downside is that I don't know how to make it not be working before the game starts now
I guess an undeclared float is the same as 0
Wait, I can declare a float at the start
Ah, but that makes the timer start immediately instead of when I start the game
I'm getting the impression I can't do this with the Update function, but using a Coroutine also seems wrong if the point is to use Time.deltaTime
Maybe a nested if statement
public void Update()
{
if (time > 0 && isGameActive)
{
time -= Time.deltaTime;
timerText.text = "Time: " + Mathf.Round(time);
if (time < 0)
{
GameOver();
}
}
}```Well, that's my attempt using Time.deltaTime
It's another case of "it works, no idea if it's correct though"
@silver fern A flag did not prevent multiple spawns of the cube
could this be an issue with my heirarchy structure and the inspector settings? I
if anyone else is interested in helping debug, I can paste my problem again
you can probably just 'bump' to the message link
if it has been some time, reposting should be fine
If anyone is able to take a look, this is my script. My issue is that I am trying to make a collectable block as I go along an infinitely spawning track and upon collecting this block a new one will spawn. However, when I collect this block, blocks rapidly spawn as long as I am inside the block and instead of the blocks continuing to spawn ahead of the user they all spawn in the starting position
I am also getting this error upon starting the program: ```NullReferenceException: Object reference not set to an instance of an object
CubeTrigger.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Base Level/CollectableCubes/CubeTrigger.cs:26)
here is my collectablemanager file : https://paste.mod.gg/tolhepdsrysc/0
A tool for sharing your source code with the world!
here is my collectabletrigger file: https://paste.mod.gg/jhghbbrhjevp/0
A tool for sharing your source code with the world!
I can also provide screenshots of my heirarchy or whatever you may need
To fix the NRE probably you want to change Start to Awake in that script
As for the infinite spawning you're probably spawning the cubes and they're immediately touching something which immediately causes another to spawn
You probably want to make sure cubes don't spawn inside other objects
oh could just touching the track or the track walls cause it?
thats an interesting thought I didnt consider
Well your code is checking for a specific tag but the only way to know for sure what's going on is to debug it
@wintry quarry Unforunately neither things fixed their issues
changing start to awake didnt fix anything
and I moved my object to not touch anything and it didnt fix it
You need to start debugging the code.
Half the time I'm not sure why something works and I have to keep going back to find the code I did it in and try to remember why.
"How did I do that again and why did it work?" lol
I refuse to paste anything from anywhere because I'll never get it
Was pretty happy recently when the game become intricate enough for things like enemy ships shooting destroyed any asteroids in the path of the shot as well as me
!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.
https://paste.mod.gg/vgcqxgesgryc/0 is this code right
A tool for sharing your source code with the world!
Why not try it and see?
im trying to "construct" (assign initial values to fields) my monobehavior. I usually just call the "construct" method after instantiating the prefab but I wonder if i could do it in awake or start
this is due to multiple "item" with different quality sharing same prefab
if you don't need to pass data to it, then you can absolutely use Awake. if you do need to pass data then it must be a separate method
i just dont like the look of it, this shouldnt have bothered me this much. maybe ill make a CustomInstantiate with many overloads instead just so i dont have to Instantiate..initialize..
but good to know it wasnt an option, thanks
Instantiating followed by an Initialization is as clean as it get 🤔
in some cases i like
disable prefab gameobject
instansiate instance
give instance data
enable instance
enable prefab gameobject
doing this means the instance's awake triggers after it's given data
? That's me
There's another person with the same display name and it looks like you caught a stray from someone who didn't double check their pings
I'm trying to oscillate the piston, but it's failing to do so. Can anyone tell me why is that so?
Oscillator.cs: -
public class Oscillator : MonoBehaviour
{
[SerializeField] Vector3 movementVector;
[SerializeField] float speed;
Vector3 startPosition;
Vector3 endPosition;
float movementFactor;
void Start()
{
startPosition = transform.position;
endPosition = startPosition + movementVector;
}
void Update()
{
movementFactor = Mathf.PingPong(Time.time * speed, 1f);
transform.position = Vector3.Lerp(startPosition, endPosition, movementFactor);
}
}
That seems like it's correct. What is it doing instead?
When I press play button, piston stays static
I doesn't oscillate
Try logging movementFactor and transform.position after you set it and see if it's actually giving you the numbers you expect
hi
Everything is just perfectly fine. Also, piston has started to oscillate now 😭
Idk why it didn't work instantly
Maybe you forgot to save.
No, I saved it also
anyone know why
{
Debug.Log("Working");
}```
in both update and fixed update will only trigger once every ~20 clicks
but setting up
``` private void OnEnable()
{
playerInput.Player.Enable();
playerInput.Player.Jump.performed += OnJump;
}
private void OnJump(InputAction.CallbackContext ctx)
{
Debug.Log("Working");
}```
will work everytime?
It's expected that it won't work correctly in FixedUpdate. It should work in Update though
No, that's how it's intended to be used
I am trying to change the opacity of a panel in my UI, but it doesn't seem to do anything
tempColor.a = 0.1f;
The color needs to be assigned back to the component after changing it
makes sense, 🙂
Use a Canvas Group and attach it to the ui.
if(currentImage)
{
var tempColor = currentImage.color;
tempColor.a = 0.1f;
currentImage.color = tempColor;
}
public class CommonUserInterfaceUtils
{
public static void ChangeImageAlphaPrecisely(Image image, float alpha)
{
image.color = new (r: image.color.r, g: image.color.g, b: image.color.b, a: alpha);
}
}
public class YourScript : MonoBehaviour
{
void Start()
{
CommonUserInterfaceUtils.ChangeImageAlphaPrecisely(respawnPanel.GetComponent<Image>(), 0.1f);
}
}
how do i performance-debug very nested calls? they eat up my pc memory pretty quickly but also are difficult to tell which function is taking most, since all of them take a bit and their sum is what eats lots of cpu time. does unity have a solution for this case?
Unity’s is practically unusable for deep profiling btw, idk
You're mixing up memory and cpu time in one sentence... What are you trying to do?
Share some profiling data(doesn't need to be deep profiling).
You can use profiler markers to debug specific code paths in details without deep profiling.
im trying to debug a deep serialization, there are two problems: 1-profiler cannot debug deep because its eating all my pc ram. 2-even if it goes through and now i can debug performance, its really difficult to tell which function call is eating most time of the cpu, because there's no metric such as "show time by function" or sth like that in the profiler
Use profiler markers. But maybe start with sharing at least some data and the relevant code.
data is just a deep json, and a custom serializer im writing. its too much to show. interesting though i will look into profiler markers ?
By data I mean profiler data. A screenshot would do.
Ok will try right now, hopefully it doesn't crash editor again.
Non deep profiling one is fine
useless without deep profiling
u get gc.alloc with nothing else
If you run out of memory with deep profiling then yea you need to use custom profiling markers
Seems like a GC issue
yes ofc. i cannot tell whats doing it the problem.
Share the Unit.Start code.
u cant tell anything. the code is deep. it calls a event bus, which calls other event callbacks etc
Having some idea of the method is gonna be helpful already
no its me
Is that some custom serializer?
yes
I see. Did you try isolating the deserialization to see if it's the main cause?
yes. and yes it is
if this is json, why make your own solution?
everything seems to be working, thanks for the help
i tried pmarkers. it does nothing useful
Must be allocating a lot of temporary object and discarding them.
Will need to add profiler markers in the serializer logic
its pointless then? i wrapped it around the deserialize. if i cant get the deep calls whats the point
you mean i wrap a recursive function?
Create an isolated test with deep profiling on?
it is isolated
this is what i get
its pathetic at this point
then try with a smaller input file?
or... different serializer thats not poo poo
You can add extra data to the marker to distinguish separate calls.
No. It just wraps a code block in a marker.
You'll need something like a memory profiler to track the allocations precisely. Though I'm not sure how you'd capture that frame where the issue happens.
Maybe programmatically..?
While the serializer is a poo poo, the object you're trying to deserialize is even a bigger poo.
i actually got 70% reduction in allocs by caching reflection
ofc the serializer is not good if i cant debug it. which is what im trying to do
If it's like 5mb+ data it's a full fledged asset that needs to be loaded as an asset.
are you using the visual studio memory usage diagnostics?
no, does that work with unity?
dunno, but if its just about serializing the json that seems to be unrelated to unity
no sadly not supported
can i not set depth or profile only 1 call deeply or sth...
unity is making sure every experience is as painful as it can get. 
What view is that exactly? Just profiler CPU?
hi
yes i think
Did you check the right side dropdown "No details", where you can enable calls?
Can someone send docs for when ui button down and up ? Couse i just find pointer down & up and I dont know if that's for mouse or buttons
yes why
I mean, that's exactly what you had earlier. 1 call deep.
Since these are recursive calls it's pretty clear that something inside the call is the problem. If you can't figure it out, maybe share the code.
i meant "1 call" deep, rather than "1-call-deep"
and the custom converters code is trimmed from there
Well, it's basically all the new objects you're creating.
var state = new JsonReaderState(options);
var reader = new Utf8JsonReader(jsonBytes, isFinalBlock: true, state: state);
if (!reader.Read())
throw new JsonException("Empty JSON");
return (T)ReadValue(typeof(T), ref reader)
Don't have the time to look through all of it right now.
Also, adding markers in all the methods(or even several in a method) might help.
why are you posting literally the ml model response?
Idk because it suggested that I do it for my code but something still doesn’t work
I advice you to read the community conduct about posting unrelated AI responses...
First debug your button. Make a simple log in your function that should fire off when you hit the button. If it does not, its not about your code yet
So should I delete it
button work, problem on my code
but i dont understand where
What did the error message say in the console. Go to the line of the code and then do debug.log(“button not working”)
console dont have errors
Had a bit of a better look. You're using a lot of Linq, which is gonna allocate tons of garbage. And you're also allocating a lot of temp objects and collections.
Also, not entirely sure if that works, but you could try adding profiler markers for each converter as well, if you suspect them being the issue:
foreach (var converter in converters)
{
if (converter.CanConvert(this, targetType, ref reader))
{
var converterMarker = new ProfilerMarker($"Converter_{converter.name}");
converterMarker.Begin();
return converter.Convert(this, targetType, ref reader);
converterMarker.End();
}
}
you ar correct for the linq. i completely removed them (.toDictionary calls etc. and used arraypool), its a bit better. i suspect whats allocating the most is the propertyName to string calls
i need to not alloc strings for prop names
Yeah. Strings are a bit tricky. They don't always allocate afaik.
You can wrap the suspicious places in a profiler marker to confirm
are ways to work around string allocations
like spans
depends on the exact use cases
Strings are for text only and should be private
Ok then I’ll delete this post for policy reasons
is there a way to generate dynamic meshes (if thats the name) using raycasts?
like draw a point where the raycast hits
and make a shape out of that
oh okay thx
yeah can be a little trickey to get used to it since you need to make complete triangles but i have used it before for building meshes from raycasts
Really? That's awesome. Good job implementing it . . .
alright can i ask u maybe when i get into problems?
how can i pause all audiosources on the scene?
by pause you mean mute?
or you mean pause mid clip, if its muting use the mixer of its an actual pause i would just keep track of all of your audio sources and do a loop and call pause on them all
or other way is via a event
put a component on all sources that are part of the global pause, have to subscribe to a event that gets invoked when you want to pause all
th an event is
How can I make the ball continue rolling where it left off when jumping? it completely stops when I jump.
Script
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.
Reduce or remove angular damping on the rigidbody
In c# I don't think so. I don't think we can stackalloc a string but you can try
i meant more do operations on existing strings without having to allocate more strings
If I do that it will look weird when moving around
Ah no, a string is immutable
yeah are mis understanding me, there are ways to work around that like spans when you just need to split or get sub strings
I think you can get a sub string view right?
Well you already have a system that changes the linear damping depending on whether the ball is in the air or on the ground. Do the same for angular damping
Or is that c++ I forget 😅
AsSpan can give you window with a start and lenght
Ah then yea that can provide a readonly sub string range with stack allocation only but
have used it a few times where i needed to parse part of a string without a allocation
I sometimes make use of stackalloc spans but many things just arent built for this
hello, I'm trying to animate some characters for my game but it doesn't work
private void Update()
{
// check for sight and attack range
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange)
{
Patroling();
animator.SetBool("isWalking", true);
animator.SetBool("isRunning", false);
animator.SetBool("isShooting", false);
}
else if (playerInSightRange && !playerInAttackRange)
{
ChasePlayer();
animator.SetBool("isWalking", false);
animator.SetBool("isRunning", true);
animator.SetBool("isShooting", false);
}
else if (playerInSightRange && playerInAttackRange)
{
AttackPlayer();
animator.SetBool("isWalking", false);
animator.SetBool("isRunning", false);
animator.SetBool("isShooting", true);
}
}
I'm animating them like that
but they just aren't getting animated
I've tried to debug like that : void Update()
{
Debug.Log(animator.GetCurrentAnimatorStateInfo(0).IsName("Walk"));
}
and it debugs true
but still doesn't work
hey can someone help me with my state machine? im trying to implement dashing but for that ill need to check if the cooldown is ready and if im not already dashing. how would i do that? i can send my code if it helps
It's best to send !code using these paste sites. Not everyone can see your file (if they're on mobile) . . .
You need to send what you have so there is something to work off . . .
Ill send it when im back but it may take a bit sorry
!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.
I have a script that adds torque to the thing Im holding. I want to use it to climb platforms like I do in this video but when I add torque while on ground it makes my player jump how can I prevent this? Also it makes me go up on air too as you can see.
how do i prevent the bullet to collide with the player? i tried to use physics.ignoreCollision and adding an offset but it didn't work
put them in separate layers and use collision matrix set them to ignore eachother
or as you said Physics.IgnoreCollision also works, assuming you use the correct references
worked thanks
hey so like how do you play an audio from an audio source without it getting cut off if the same sound is played again before the first one ends?
probably using OneShot
wdym?
PlayOneShot instead of Play
idk I'm using this rn vvv
sound.Play();```
ok so now based suggestion I made, which part do you think I'm referring to
This is intended behavior when giving unnatural torque to a long rod. Maybe incorporate it into your gameplay?
my terrain is getting weird when I try to paint on it. I'm using a default brush and the default terrain shader. the black artifacts can be painted over to be normal again but I have no idea why it's happening
this is a coding channel
ok!
So when is if or a case preferred over one another if you're just checking something like .tag="whatever"?
I switched this to case, seems better.
CompareTag is better than ==
forget tag.. components are the way
yeah its the core to unity gameobjects
if(other.collider.TryGetComponent(out Player player)){
player.DoSomething();```
Confused. lol (usually am for a while)
you never use GetComponent ?
anyway much safer and efficient way to find something
and instead of limited by tags
Interfaces are the big one if you need a common "tag" to work with
Just trying to understand why I need to look at components of an object collided with, Im confused
I'm sure if you google it there's plenty of threads of the topic.
but yea having a "common" tag among more than 1 gameobject would be nice (but since we can only have one)
at the moment this is how I had to do it
yes one of the limitations of tags
but even calling it a "tag" would be doing injustice, its much better than that.. it will make sense soon enough
I started with just naming enemies "Enemy" for example but I wanted a lot more complexity to it
At the moment the asteroid has this. Did the player hit the asteroid (with himself) or did any of the weapon types hit it, etc. And yea, 3 tags there just for that.
What else can be hit that isn't in the switch statement?
at the moment nothing but there's a lot more to add
That's just the asteroid script
this logic doesnt look great either. what is this for anyway?
If a weapon projectile collides with the asteroid or a player or an enemy ship, etc
(it goes boom)
Just uses the trigger to know it's been hit
right. If it was me id not use tags but check for a specific component (perhaps using an interface?)
Ideally, you'd use layers to prohibit collision between objects that shouldn't collide with it to begin with. Then you'd filter by either tag or component. In your case above with using tags, I would just check
-if it was a player, bump then return
-else play dead and disable the component or something if you aren't wanting it to occur again.
its okay to start off but as things advance, solutions that only work for 1 specific thing start to break down
Problem is beads dont move like I want. Sometimes they collide with the sticked bead and cant turn past it so I cant stick other bead to platform.How can I solve it?It sticks by making the sticky static on collision ith tag "ground"
I mean I could check if it has the enemy projectile script and then I'd know it was a weapon hit
That would kind of be like having a common tag
well no because knowing it has a specific component or a component implementing an interface already makes things easier
e.g. making the player and enemies share the same "bullet" type
Is that what you guys are saying by look at the object that hit it's components? The script being common between the things I want to check.
That's the only way I know I could identify it correctly at the moment with a component
you use inheritance to share logic for taking damage and then the bullet uses this, allowing it to work on many types of objects
Yea I haven't gotten to inheritance yet I'm about a week in
Eventually I'd have it behave differently depending on what exactly hit it, weapon type, object etc
As well as asteroid mass, etc
hello, I'm trying to make a stealth detection system using Physics.CheckBox, and i set the center at the position the AI is in. Basically the box should move with the AI, and if an object with the Player layer enters the box, then the AI should chase the player. the only issue is that the AI wont chase me when i'm within the box. I dont want to use raycasts as I want the AI to detect me from all directions. I also dont want to use CheckSphere as I dont want the AI to detect me past a certain height since it scales uniformly.
I'm kinda lost lol
is the checkbox detecting the player?
maybe BoxWidth_Sight and those other variables are 0
or maybe the player is not on the right layer
they are public, i used gizmos to visualize them
<@&502884371011731486>
<@&502884371011731486> spam
i already checked, i also made a cube and put it on my Player layer and it wasnt detected for some reason.
did you assign whatIsPlayer in the inspector?
Are you assigning the layer mask from the inspector?
yeah thats whats confusing about it, i can send a picture if you want
You're going to need to if you want to assure folks that you've got it set up correctly
what's confusing about it?
ok one sec
just that its not working when i've already set the layer
So is it detecting the player?
the warnings aren't affecting it btw, its just some code i havent deleted
Log to see if check sphere and box are ever true
not sure, it looked normal in the gizmo. one sec
its not true right here
only for attacking
but not for seeing my player
i can see that BoxLength_Hearing is negative
PlayerInSightRange is false
would that affect it? i can check again in the gizmo
of course it affects it, remove the -
from all of your numbers
ok
does it work now?
still changing the values
yeah it works thanks
silly mistake
So I'm trying to make the localscale.x reach the value MaxScale with the rate of scaleFactor, now from my understanding of lerp (and the debugging of the infinite loop lmao) that sincee scaleFactory is constant it'll not truly reach the value unless I set t=1, or scaleFactor = 1. am I correct?
The overall goal is I'm doing a melee attack that stretches the weapon forward (and then return it but I didnt do that yet)
at t = 1 lerp will return the max scale vector
using this will let you step better towards your goal
or do a lerp properly that has a fixed start + end and moves lerp from 0 to 1
Man, my brain just does not hold information. I just wanna make an enemy rotate to face the player, and I'm sure I've done that exercise at some point during the course I'm doing, but man, brain just empty
enemyRb.transform.LookAt(player.transform);
I am often in disbelief that some solutions are so simple when I google them
Small issue however that my enemies are now doing the limbo when I jump
in your look at, for the y part of the vector just feed in the enemies y position
Vector3 lookPos = player.transform.position;
lookPos.y = transform.position.y; // keep enemy's Y the same
transform.LookAt(lookPos);```
practically clamps that axis
That does work, so I should probably take the time to figure out why
I should also make it so the cops colliding with the dog destroy it like it did when they were cubes
b/c it just takes the position (that would be making u tilt)
and instead its shifting its Y (up and down) position to match the enemy
if u use a Debug method to debug the positions (each one) you'd see they just stack on top of each other (ignoring) ur up and down movement
I think I get it
That's gonna be hard to like, keep in my head though
My brain doesn't like the solution not being one line. It sucks, but it's what it is.
Just instinctually it's not gonna think to make variables instead of doing it all inside LookAt
u can make variables if u want..
"modifiedLookPosition" is normally wht my LookAts() target
theres other ways i imagine.. thats just the one i learned to use
Vector3 modifiedLookPosition = new Vector3(
playerTransform.position.x,
transform.position.y, // clamp Y
playerTransform.position.z
);
transform.LookAt(modifiedLookPosition);``` its like doing this
I was just about to ask if you could do it with a new vector3, but I was worried I'd look stupid
nah its just shorter to copy the whole transform and then modify the y afterwards
looks cleaner imo
I think if modifiedLookPosition is on a single line it might be easier to read, imo
do it whatever makes the most sense to you
player.position.x is wrong isn't it? Shouldn't it be player.transform.position.x?
Yeah, I'd assume "player" would be a GameObject
Hello guys im having problems with ragdolls. Basically my issue is that my ragdoll dies, i disable the animator and then the ragdoll has some weird issues such as it goes through the ground or sometimes acts violently.
However, when I turn off the animator from the window, the ragdoll falls down normally and naturally as I intend to do it. I tried to troubleshoot the issue and I can say that the issue does not arise from the colliders on the body overlapping. Please help>
Here is a video to show what I am taking about.
I fixed it guys nvm
Is there a way for lines like this in code which will cause the build to fail, to have them ignored on build? UnityEditor.EditorApplication.isPlaying = false;
yes but out of curiousity whats the purpose of it
There are certain things smilar to that in scripts that can cause the build to fail. Just wondering if the build process can ignore them.
well yeah UnityEditor.EditorApplication.isPlaying does not exist in builds
<@&502884371011731486> spam
it's editor exclusive
the best way to solve this issue kinda depends on why your touching it
Change the Collision Detection property on the rigibody component to something else like continuous dynamic.
https://docs.unity3d.com/6000.2/Documentation/Manual/platform-dependent-compilation.htmlcs #if UNITY_EDITOR //... #endif
Nice, thanks. It was mostly an educational question that I was curious about. I use the Pragma lines sometimes to stop filling my log and figured something similar worked for compile.
When Unity builds a game, what happens to Debug.Log statements? They can't do anything in a build that I know of, so are they discarded at compile time?
nothing happens to them, they still run
when done debugging those are usually cleaned / taken out . Usually you have a custom logger anyway
Seems like an oversight on Unity's part but okay
not really, allows you to log/debug the build
if you have developer mode enabled they show up in the console window
For the healthbar over the enemy's head, I not only want it to always face the camera (billboard like) but also stay horizontal to the camera. Is there a simple trick I am missing to do this?
Well, staying horizontal just means you change only the y-rotation, right?
So then, one way is to find the vector from the enemy's head to the camera, create a second vector using the first one's x and z coordinates, use atan2 to find the angle, convert it to degrees, then set the GUI's rotation using euler angles
Pretty sure they're stripped out in a release build(non dev), but might be wrong
OK, they don't get stripped out apparently:
https://docs.unity3d.com/6000.2/Documentation/Manual/class-Debug.html
Learn something new every day.
Looks up how to format C# beautifully because he hates looking at anything less
Hmm, or does VS Community have a button for that lol
Nothing changes. Guess I'm a pro formatter already. 😂
is there a supported api let me deep clone a reference type object like classes
What are you trying to use this for?
Unless its entirely out of your control, you should implement a copy constructor
Hello, guys! I’m working on a cannon in Unity. The cannon’s initial rotation in the Editor is -183° on the Y axis.
When I try to rotate it via script using transform.localEulerAngles or Quaternion.Euler, the Y value sometimes shows -360°, instead of the original -183°.
Why is Unity converting it like this?
Basically, it does this with every game object I am trying to rotate. I have tried to initialize the rotation of it and it worked. I am just curious and want to know the source of the problem?
can a experienced guy help with smthin in unity?
so so
am making a simple game
in which a like a circle is hanging from a chain and i can move it with mouse and release it
i cant get the script to work i really need help
You want to make this functionality you are describing?
Where is the script and what you do ?
The same rotation can be represented as different Euler angle values. Rotations are stored internally as quaternions and converting a quaternion to an Euler angle can produce any one of the possible representations
How would one destroy every child from a script in their parent
That's ruthless 😛
good thing i added script in there...
foreach(Transform child in transform)
{
Destroy(child.gameObject);
}
yh i did that but i just saw that the if statment that its in was not working lol
i forgot to debug(like usual hehe)
It's always something that you think "Oh geez. Duh."
fr
whats wrong?
You see this kinda lie jittering and object tearing
when rotating fast
This is the script that is being called in LateUpdate but I dont htink the script is a problem
What version of unity?
Why are you not using the new input system?
If you plan to add multiplayer you will have problems(from what ive heard)
Nah it is a singleplayer game
Also no runtime keybind changes(the keybinds are hard coded)
But for the rest of the keybinds
So... do you maybe know why that thing with camera is happning?
I mean it cuz the sense is high(atleast thats my assumption)
It should be allowed to rotate this fast
Also ive had to look really close to see any problems, im sure it wont effect gameplay
Everyone that play tested the movment noticed it
Turn on vsync in the quality settings and in the game preview window
Hello! so, I am trying to make a interactive chess piece following a tutorial video but.. I run the game and clicking on the chess piece object and nothing happen. I have no clue why.
I check everything out.
Here is what I checked:
the object attached Box collider 2d ✅
I attached the script to the object ✅
here's the part I wrote in the script to run
OnMouseUp()
private void OnMouseUp()
{
Debug.Log("You clicked on " + this.name + " at position: " + xBoard + "," + yBoard);
DestroyMovePlates();
InitiateMovePlates();
}```
The debug I wrote didn't even shows up in the console when I try to click on the chess piece.
Make sure the old input system is enabled. OnMouseUp doesn't work in the new one. Instructions are here: https://unity.huh.how/input/input-system/input-handling#revert-to-the-old-input-manager
thanks
hey i need help and it is complicated
So i have an NPC self made in blender with an rig and i have animations fo it and it work bc i have it on my player and i want that this NPC walks with nav mesh and it does already but the animation parameter thing dosent work can someyone help me? PLEAS 
Yes i know but the code is wrong not the animation
post your code then
📃 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.
A tool for sharing your source code with the world!
Hey, I tried doing this in order to be able to validate the value(similar to what odin offers) in the editor, however, the second line crashes the editor.
Is this not what I am supposed to do or something?
var capacity = _shotVFX.GetParticleSystemInfo(0).capacity;
var spawnCount = _shotVFX.GetSpawnSystemInfo(0).spawnCount;
I can temporarily work around it by making the spawn count a variable, but this is quite odd regardless.
Please @ me and thanks in advance!
And what's wrong with the code (other than, it's not working)? Are there errors in the console?
No so the problem is the animation idle is played all the time so what i mean is the parameter isnt used correct
So it isn't a code issue?
btw, I just noticed that capacity isn't working either, it returns 0.
I switched to a property for spawn count as it's a good practice either way but I can't really get capacity any other way afaik, no?
Are you going to elaborate?
What is that?
Explain why it's a code issue.
I've got no audio so I'm not understanding what the video is illustrating. Assuming your animation is set up correctly, I'd try logging some values to see if they're what you're expecting them to be. These in particular: cs // Normalisieren basierend auf Agent-Speed float normalizedZ = Mathf.Clamp(moveZ / agent.speed, -1f, 1f); float normalizedX = Mathf.Clamp(moveX / agent.speed, -1f, 1f); // Animator-Parameter setzen animator.SetFloat("MovmentZ", normalizedZ); animator.SetFloat("MovmentX", normalizedX);
The move values, speed and normalized values
i have an idea but how do i active the preview window in the right low corner? where i could see the animations
WHAT PLS GUYS 🙁
I dont know what is happening
have you tried googling for that?
no, my internet is currently shit and i can't load your video lmao
trust me you will be lost when you see this
it is very wierd
and yes i have watched like 20 tutorials but nothing works
can someone please help? how to make 8 directional sprite 3d????
i searched for every vid on ytube and everywhere but cant find this guides
bump
this is the code channel, go ask in #🏃┃animation
The course I'm doing is trying to teach me variable attributes, but I'm not really sure I get them. I've tried to make them simple to understand rather than the very jargon-y ways that they tend to be explained
**Public **- Visible in inspector and can be accessed by other scripts
**Private **- Not visible in the inspector and can't be accessed by other scripts
**[SerializeField] **- Visible in the inspector but can't be accessed by other scripts
**Protected **- Not visible in the inspector but can be accessed by other scripts(?) (ones that inherit the same class? Since I've only ever seen MonoBehaviour I don't really know what this entails)
**const **- Makes it so a value can't be changed, this was in JS so I understand it (I hope)
**readonly **- You set the variable when you create the object but then never again. Not really sure how this is different to const? Does that mean you can only define it once? Like you declare a bool and then can initilize it as true/false later, but then it's locked forever after?
**static **- I honestly have no idea. "If you want to have a global variable to use anywhere in your code at all times", I don't know what that means or how it'd be used.
hello guys, im a bit new to unity and to c#. What do you recommend me to do to learn c# ?
Thanks
a few notes:
- most of these are modifiers, not attributes.
SerializeFieldspecifically is an attribute, as indicated by using[]with it. - access modifiers are also in lowercase
constisn't jsconst,readonlyis more like jsconstreadonlyis for a variable that doesn't get reassigned.constis for a variable with a compile-time constant value.
staticis also in js, it's an OOP thing. it means the member belongs to the type rather than an instance.
Blame the unity course
how do I make my player move?
It's also now trying to teach me event functions. So tell me if I've got this right.
**FixedUpdate **- For use with physics, called before Update
**LateUpdate **- For use with cameras, I presume it's called after Update
It's also trying to teach me Awake, but with no context it doesn't really make sense how and when to use it.
Don't worry—the documentation explains each event function and where they're called in the Unity life cycle . . .
The documentation is really hard to read though, it explains stuff in the most jargon-filled unsimplified way it can
So Im trying to boil it down to a level that I can understand it
There are many different ways; it depends on how you want your player to move . . .
- velocity (Rigidbody)
- Kinematic (Rigidbody)
- Unity CharacterController
FixedUpdate isn't called before Update (or at least it's not a useful mental model to think that it does.) It runs at its own cycle
Why does the Unity Pathway lie so much then? 😂
[The function event order](https://docs.unity3d.com/Manual/execution-order.htmll) seems pretty straightforward to me. Take a look yourself . . .
If it says that it runs before Update, that's technically true but not useful information at least to a beginner
FixedUpdate runs before Update in the Unity lifecycle . . .
It does but that's not its defining characteristic
Yes, you can set how often it's called, but during the same frame as Update it will always run first. That's the important characteristic . . .
No it isn't
If someone who doesn't know Unity asked a one-sentence description of FixedUpdate, that sentence wouldn't be "it runs before Update"
What would it be then?
"It runs at fixed time intervals instead of every frame"
What defines the time intervals?
Like if I'm literally just changing Update to FixedUpdate
It's set in the project settings. 50 times/second by default.
called before Update
keep in mind this isnt' called before every update.
I'm currently trying to make a velocity movement tÿpa thing and then jump mechanics
That's cool. You should be able to find some tutorials for movement and jumping using velocity. I'd start there . . .
there’s tons of tutorials and I don’t know where to start honestly
Don't fret over it too much. Just pick one, watch it. If you don't like, start a different one . . .
alright sounds easy enough
What matters is actually starting. Dive right in . . .
i came back to unity after like 4 years and faced my worst enemy so far: ONTRIGGERENTER. no matter what i do it just... doesnt work.
my setup: two rigidbodies, two colliders, one is trigger. the enemy box has a boxcollider2d and a dynamic rigidbody, the bullet also has a dynamic rigidbody but circlecollider2d set as trigger.
in the script for the bullet i listen for triggers enters but it just doesnt work. tried that on the enemy too but didnt work.
im... not sure what to do. i also clearly remember struggling with the exact same thing before but i dont remember what fixed it.
You'd have to explain and show your code. We don't know what move.x is . . .
tried mishmashing everything too: enemy as trigger and bullet as trigger, nope. both triggers, no (makes sense because two triggers wont collide and wont make an event)
OnTriggerEnter is not the same as OnTriggerEnter2D . . .
what
One method is for regular 3D physics. The other method is for 2D physics . . .
Look at what type of colliders you have on your objects . . .
Are you making a 3D or 2D game? These are the signs you have to pay attention to . . .
but for some reason didnt do that, prob because it gave a warning about argument types which i didnt change
YAY it worked
Does anyone have an Idea why my player movement "lags" when I dont have my player open in the inspector? this also happens in builds qwq
I have my Movement in FixedUpdate and my camera movement in LateUpdate
You'll have to show the code
void HandleCameraMovement()
{
mouseX = lookInput.x * cameraSensitivity * Time.deltaTime;
transform.Rotate(Vector3.up * mouseX);
mouseY = lookInput.y * cameraSensitivity * Time.deltaTime;
currentCamAngle -= mouseY;
currentCamAngle = Mathf.Clamp(currentCamAngle, -maxCamAngle, maxCamAngle);
cam.transform.localRotation = Quaternion.Euler(currentCamAngle, 0f, 0f);
}
void HandleMovement()
{
if (isSprinting && currentStamina >= sprintMinStamina && isMoving)
{
movementSpeed = sprintSpeed;
currentStamina -= sprintStaminaUsage * Time.deltaTime;
}
else
{
movementSpeed = baseSpeed;
regenRate = isMoving ? staminaRegenRateWalking : staminaRegenRate;
currentStamina = Mathf.Min(currentStamina + regenRate * Time.deltaTime, maxStamina);
}
Vector3 forward = cam.transform.forward;
Vector3 right = cam.transform.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
Vector3 targetVelocity = (forward * moveInput.y + right * moveInput.x) * movementSpeed;
movementControlFactor = IsGrounded() ? 1f : airControl;
currentVelocity = Vector3.Lerp(currentVelocity, targetVelocity, (moveInput.magnitude > 0 ? accelerationSpeed : decelerationSpeed) * movementControlFactor * Time.fixedDeltaTime);
rb.linearVelocity = new Vector3(currentVelocity.x, rb.linearVelocity.y, currentVelocity.z);
}
Don't multiply mouse input by deltatime. You'll have to then lower the sensitivity after removing it
Alright, thanks!
but why does it work when I have the player open in the inspector? that makes no sense to me at all
With deltatime the mouse movement depends on framerate and things like that can change the editor's framerate
That makes sense yeah qwq
Thank you!
That did the trick, thanks!!!
I do wanna ask real quick, in scripting, when is it ever ok to use Numbers instead of Variables?
You don't want to use "magic numbers" in formulas because it's not very descriptive and you will forget why you put it there. Also having variables will enable you to easily tweak formula in the future, especially if you use one more than once.
I see, tysm
Can someone explain why my secondary camera isn't in the right position?
This is a code channel.
Okay, this is how the camera works. Better?
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
public Vector3 offset = new Vector3(0, 5, -7);
// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}```
have you tried debugging player.transform.position or the full result of the addition
What's the initial position of the vehicle?
Not 0,0,0, which might be the problem
your offset is different in the script and in the inspector
Yeah, but the one in the inspector is the offset for the secondary camera
It does seem to have been that it was adding together the players initial position in-game and the offset
If you want the positioning to stay where it is in the editor you can set the offset at start:
void Start()
{
offset = transform.position - player.transform.position;
}
or make the camera a child of the vehicle and set the rotation in code instead of position
That's what the course had me write. The guy in the video changes the same things as me and it works fine. This is like, the first prokect they have you work on. It's not my fault it's using jank code.
what video?
One of the Unity Pathways
The guy in the video has the vehicle at (0, 0, 0)
can i know where i can get solution for ui + code
both are good, pick one of the relevant channels
i cant find any other helping channel either than code beginner
Do u guys usually use state machines to switch between character status like walking, crouching, jumping etc. ?
did finished this course 2 months ago
You can use a state machine or separate components for each mechanic (walk, run, jump, etc.) . . .
make offset to 0,0,0 in inspector i believe it will be fine then
I find it quite complicated. It's more like a design choice for the long run
Why doesn't Application.targetFramerate change the FPS cap in the editor's game view?
How do I make a camera active with code? enabled doesn't seem to do anything, setactive doesn't even come up as an option, active is apparently obsolete
SetActive is for GameObjects rather than components
so you would do camera.gameObject.SetActive
myCameraComponent.enabled = true
enabling a component on a deactivated gameobject won't do anything, so that might be why that didn't seem to do anything
oh just saw you edited about SetActive.. also you should either SetActive gameobject or disable/enable component itself
.enabled comes from behaviours not Gameobjects so GameObject.enabled doesn't make much sense
public void setFramerateCap()
{
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = targetFrameRate;
Debug.Log("Changed target framerate to " + targetFrameRate);
}
void Start()
{
camera1.enabled = true;
camera2.enabled = false;
}```Well that's what I have in my Start, and it doesn't seem to do anything. Keep getting console messages about 2 listeners.
because disabling the camera doesnt disable another component, the Audio Listener
are the camera's gameobjects deactivated
so you should just deactivate the gameobjects in this case
Cinemachine makes this such a nice process
usually, Virtual Cameras > Multiple Camera components
Cinemachine keeps 1 Main camera componen but switches the view / setting through Cinemachine Cameras
Well the overall of what Im trying to do just isn't working, nothing seems to be affecting the cameras
are the camera's gameobjects deactivated
Ive tried both
both what, exactly?
The script doesn't seem to change anything either way
did you put a log to see if the code is even running
Both turned on, both turned off
do you see the checkbox beside the camera component changing
what are we looking at ?
Hello people!
Lil' question; What would you consider to be a simple (code-wise) yet impressive - looking game to make?
I have very little coding experience yet, but I'm about to start my TDR (long-ass paper on something (theory and practice) and I want to use it as an opportunity to learn a bit more :]! However, I have limited time (around 7 months, more or less) and I want to make something that takes some effort without it consuming my life
I'm trying to cap the fps
Because my player jumps higher at higher fps
In the build I have higher fps compared to the editor
perhaps try to fix the fps dependency then
puzzle game
Well I want to be able to see the difference
show code for that
https://xyproblem.info @queen adder go give that a read, you're targetting the wrong thing to fix the issue
it should work fine though, at least syntax wise
did you verify that code is running ?
if (Input.GetKeyDown(KeyCode.Space) && isTouchingGround)
{
float jumpForce = jumpStrength * rb.mass;
Vector3 jumpVector = normalVector * jumpForce / Time.deltaTime;
rb.AddForce(jumpVector);
}
This is in update
I'm dumb
you probably want a Impulse
that / Time.deltaTime definitely doesn't make sense
why not just
rb.AddForce(jumpStrength, ForceMode.Impulse)
Impulse?
btw, you could also use forcemode velocitychange to make it so mass isn't taken into account
impulse already takes into account mass
that way you don't need the * rb.mass either
I want mass to be taken into account
rb.AddForce(jumpVector,ForceMode.Impulse);
What's the default ForceMode?
then that would be / rb.mass, but yeah, both Force and Impulse modes already do that
Force
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
if (camera1.isActiveAndEnabled)
{
camera1.enabled = false;
camera2.enabled = true;
}
if (camera2.isActiveAndEnabled)
{
camera1.enabled = true;
camera2.enabled = false;
}
}
}```Okay, I messed around a bit more, but this doesn't seem to be working.
AddForce should not be called in Update unless you use Impulse
Any specific sub-genre you'd emphasize?
okay i still want to be able to cap the fps
have you done any logging to see how the conditionals go
Yes
...and the result was..?
Not really the point, puzzles can range from very easy to make (code wise) and rely more on the Game Design aspects
ok, we don't know what those logs are
buddy if you want help you have to provide adequate info
Can you not infer?!
Alright! Thank you
you have 5 booleans here
what are these logs supposed to represent ?
im not gonna assume which ones you chose to log and in what order
One is true, one is false, and it's about switching cameras. Guess.
we can see the result, we have no idea where you placed these..
something called context
you've been providing lackluster, inadequate info for a long while
you need to get better at asking questions
support is a 2 way street
And if you were logging inside of both if statements you'd be seeing the problem
So, guess
we are not psychic, and what you assume are "obvious" logs are not guaranteed. we deal with a bunch of bullshit. you can't be bothered to write out 1 sentence clearly explaining the thing you so badly want us to magically infer?
Becuase if I write out the full context of everything it becomes a massive text dump and then you also get annoyed about that
I mean it's fair to ask us to infer what their logs are. I choose to infer they put them in exactly the places that would tell them the obvious problem, so I don't even need to answer it any more!
Isn't inference grand?
should work fine if its a build on PC platform
let me guess, you dumped a ton of context without actually saying the issue and got burned for that.
asking good questions is a skill. you need practice. you won't get better if you're determined to not give any useful info whatsoever
Is it mobile? Mobile had some fucky third thing you have to do to quit IIRC
I was trying to call it from a button and it wasn't being called. That was the problem, not Application.Quit()
I'm just trying to figure out why Application.targetFramerate doesn't actually cap the fps
Sometimes you find the answer the moment you hit send on the question
happened twice already maybe i should think more before sending

Okay, I found the problem on my own. It's not that pressing C isn't changing cameras, it's that both things become true as it runs the script so it is doing something, just so fast it's inperceptible.
Yep that's the thing you'd have seen with the logs in the places I inferred you put them
Basically, the problem was that I needed an else if statement
Anyone who looked at that could have told me the same thing without additional context
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
if (camera1.isActiveAndEnabled)
{
camera1.enabled = false;
camera2.enabled = true;
}
if (camera2.isActiveAndEnabled)
{
camera1.enabled = true;
camera2.enabled = false;
}
Debug.Log(camera2.enabled);
Debug.Log(camera1.enabled);
}
}
```something like this would not be out of the ordinary, especially so in a beginner channel. again, *we aren't psychic.*
hey I want to mak a timer that does a specific code block for 3 seconds continously until if finishes
this executes way too fast (the function is called on a button press not in update)
how can I do something likee this? can I run the code continously with a coroutine?
I'm not talking about the logs, just looking at 2 if statements one after the other that switch the enabled status of the same things, people who aren't me could see why that's wrong
bump
that's doing it all in a single frame. you'd want a coroutine
also for future reference,
!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.
We aren't here to fix your code.
We're here to teach you how to fix your own code
while loop here does everything before running the rest
Putting logs in both if statements would show you that both were running and demonstrate to you what the problem was so you actually understood it and came to the conclusion on your own
Which worked by the way
I see
but to my understanding if I do someething like
yield return new waitforSeconds(t);
would pause the rest of the Coroutine until the wait is over
yeah.. then don't do that
you can put the same while loop just in a coroutine and add yield reuturn nullinside while loop
you'd want to yield return null in your while loop
you would use a yield return null; to wait 1 frame and then continue with the action
Oh I see thanks
How do you do this inside the animator script? Doesn't appear to work the same way.
that's not how setbool works nor how it's spelt
Irrelevant. It's there to show what I'm doing.
What is setbool
considering it returns animator then probably something you want to run it on
you have an Animator, you have a name, you know it's a bool, and you have a value you want to set.
how exactly does it "not appear to work the same way"?
consider.. using words, like "how does setbool work"
this could be anything from setting a property to accessing a field lmao
I'm just going to ignore you. You are annoying.
what is going on today, damn
you have to assume people you show problem to are 6 year olds that have no idea what you're showing (no really its a technique), the more you explain it the better...hell you might even end up rubber ducking the problem and solving it all on your own..happens often..
Think I got it anyway.
yeah.. so.. it works exactly the same way
wonder what this was about 😆
Doesn't appear to work the same way.
I like to think of it as "Ask your questions as if everyone is an asshole genie who will find any way they can to technically answer it"
this shows an incredible lack of understanding of how c# works if you found SetBool in the docs and then did . . . that.
perhaps consider stopping what you are doing and going through some beginner courses, like the ones pinned in this channel
Lol I like this one
It was a fucking example to show what I needed to do. As I said. Can you comprehend that?
lol someone's mad
you can lead donkey to water...but you cant'......fuck it lets drown it
examples usually need to make sense though
Consistent arrogant answers do become annoying.
show me where i was being consistently arrogant to you
And constant people who don't put any effort into their questions and expect us to just know is draining
Well if you are unintelligent enough to figure out what I'm trying to do from an example that's on you buddy.
Or you could ask.
ah yes, i'm the one being unintelligent here
ah yes, good way to get help around here.. insult the only ones with the patience to entertain your foolishness
please, do point to where the arrogance was.
seriously though. you asked about a thing that "apparently didn't work as usual"
it turns out that it works exactly as usual. if you'd just wrote the actual code rather than the weird pseudocode you'd see that it does, in fact, work
You won't get any civility from being arrogant.
willingful ignorance is also a form of arrogance, so you're arrogant in that regard..
had people actual put effort first learned the actual basics instead of running here with every basic things , we would probably avoid half these questions..
to be blunt here: no-one here is being arrogant. you're ignoring advice everyone's trying to give on basic skills.
the sooner you realize that you're lacking, the sooner you can start to improve them.
If you can't handle questions attempting to get pointed in the right direction you might as well not say a word if you can't respond with an answer that doesn't make you come off as arrogant. You're in #code-beginner.
Literally what did you mean by "did not work like normal" though.
That actively made your question harder to parse because it implied that your code was "the normal way" in which case we would need to know what the hell you thought that was supposed to do
If that doesn't make sense to you, you'll never be helped.
buddy.. we did point you in the right direction. several times.
code-beginner not kindergarten
digiholic pointed out researching the things you're trying to do and docs.
me and nav pointed out what info you did have available.
boxfriend pointed you to rechecking your skills.
everyone here is trying to help. none of us can if you don't accept it.
There's that arrogance. He still hasn't learned.
ok, point out to me where the arrogance is. perhaps i can learn then
this has to be a troll right?...right?..
huh, that's not a bad explanation.
another question about this
how do I ensure at all times that both the timer and the fillAmount for the image finish in the same time
Easiest way is to do them both in the same loop
i generally use a single variable for keeping track of time and then lerp other values to keep them in sync
Then they can't desync
(also with how you've set it up, they can't finish at the same time. timer takes 3 seconds, but fillAmount takes 10/3 ≈ 3.333 seconds)
yeah that's what I mean
I want using the startingTime to ensure that it takes 3 seconds
maybe you want to Lerp if you want it to take exactly 3 seconds to get to Full
can you suggest me somewhere from where i can learn unity its my 3rd month trying to learn unity constantly
and tbh idk if i really know the basics
yeah just lerp instead of trying to figure out the math tbh
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the math isn't hard, but lerp makes it way easier (and harder to mess up accidentally)
no, you wouldn't be using deltaTime there
aside from Learn sent, check the pins here too for the general c# stuff you will need as well
there are multiple moving pieces to gamedev
(the engine API you're using and the coding language itself)
i usually use this pattern
float elapsedTime = 0;
do {
elapsedTime += Time.deltaTime;
value = Lerp(MIN, MAX, elapsedTime / LIMIT);
} while (elapsedTime < LIMIT);
does that make sense?
yeah it does
thank you
yknow thinking about it now that probably is wrong. the += Time.deltaTime should probably be after taking the current value.
its a basic percentage and so we always get the normalized value
Lerp wants t to be 0-1
i usually do this too
apparently Vertx does too in https://unity.huh.how/lerp/coroutines
!warn 356111028213383170 If you are not using the channel for Unity questions don't spam the channel with off-topic. If you continue insulting people you'll be gone from here very quickly.
@marik82 warned
Reason: If you are not using the channel for Unity questions don't spam the channel with off-topic. If you continue insulting people you'll be gone from here very quickly.
Duration: Permanent
i have a question which i couldnt solve in 15 hours its more than 2 weeks tough did 10 hours of chatgpt youtube etc replaced code many times still not fixed.
the problem is i made a joystick on left side for playermovement and the right side 60% of screen i gave it to touchpanel where i can rotate screen but when my first finger is outside of that touchpanel area(on joystick) then the 2nd finger which i use for controlling the camera movement does not works
you mean doing += before taking the value?
i mean like 🤔 on the frame it's called, it should be t = 0, right?
not sure if i am right though
if you start it with a high deltaTime it'll be done immediately instead of the next frame
maybe that's better.
ha yeah goes above my basic brain, definitely something to test I suppose
maybe it doesn't matter lol
hard to say without seeing the complete setup...
if you're brand new though imo touch inputs and UI stuff should probably be a bit further in priority on what to learn
It definitely is. I'd pick which one is easier for you to learn or implement and start from there . . .
i guess i learned alot of it rather than brand new
tbh if there was someone or some channel etc from where i could understand where i am standing now and what should i do would do alot of help or at least see my projects and review it