#💻┃code-beginner
1 messages · Page 392 of 1
great, thanks!
Note that in the context of your for loop and as the sole statement for the iterator, it'll produce the same behavior - relative to having the symbols before/after then variable.
Is there an easy way to lerp two objects at the same time in one script? I'm trying to lerp both ends of a line renderer in different directions. Is it easier to just have 2 line renders?
You'd just lerp the two points (ends) that you're wanting to lerp to wherever they would need to go.
Why wouldn't they?
Wouldn't they lerp 1 after another?
Also, if you don't care about the transition process, maybe simply have the points move towards the targets.
Code either happens and finishes immediately or returns control to not finish immediately. You'd lerp/move the other point then - assuming you're actually lerping and not just setting your position to your destination.
what do you mean by that?
I have a question.
I've seen a couple of times thing, where some random parts of code is encased in asterisks(*), like:
points *+= diff;*
or
var particle = particles*;*
What's the point of this?
Edit: formatting is hard
There's a += b that is a shorthand for a = a + b.
yeah i knew about that, just like it looks like it was intentionally encased in them for some reason. IDE throws errors on that
could it be some formatting error? because both examples are from discussion.unity
As for the second example, you may need to cache materials, particles or other values to be modified and later assign back to those properties - they're not directly modifiable like members of the Transform. For example:cs var position = transform.position; position.x += ... position.y = ... transform.position = position;
Pretty sure the asterisks were intended for the embedded platform and not actual code. On discord, asterisk would italicize text. For example, *+= diff* would become += diff.
Yeah, looking at those messages they are pretty broken. Thanks 
Reverse your if statements
Generally your code should have a single happy flow that ends at the bottom. Right now your ends somewhere in the middle
If you reverse your if-statements you can create guard clauses that make it clear what is being checked against, and what action is taken when this fails
Especially in your case it really avoids nesting your code multiple times
Alternatively.
Move the Debug.DrawLine to the top of the method
Add a Return after the else if
Then you can remove all of the following else statements
You could have a bool reset= true declared at the start of the method and set it to false when you don't want to reset. Then at the end check the bool and reset if needed.
Or even better, just return of you don't want to reset.
That would save you from writing a Matroshka like that.
Code monkey?
nah
my own code, didnt watch any tutorials like 6 months
This is the way
Is there an option to not round values when converted ToString("F2")? Just want to kinda cut off the value, not round it
Well I guess, truncate is my only option and no tostring parameter
try "#####.00"
Ignore that, it rounds as well
Trying to create an Audio Manager, would using enums that correspond to the sounds be better, or just ids?
public static float Truncate(this float f, int digits = 2)
{
float power = MathF.Pow(10, digits);
return MathF.Truncate(f * power) / power;
}
Hi, Unity is not detecting key presses on my system. Any help?
Script not attached to an active gameobject?
Input System not set to Old or Both ?
Ok got it.
i have this discord activity script
but when i stop the game it just stays instead of disappearing
private void OnApplicationQuit()
{
if (discord != null)
{
discord.Dispose();
discord = null;
}
}
Maybe simply add this?
i tried but then for some reason it doesnt even turn on
wait its not working either way now
idk bout that
Wow, so you can do something like that
Well, it does seem it should be disposed.
no its something else now
Don't you have to wrap it in a catch?
this guy didnt
it was working a minute ago
and now it aint
i didnt even do anything

Well, it's not working for you, but you're still sure this guy still implements it the correct way
Simply catch a ResultException
I'm not sure when it appears, but it should work by only doing that
It could be because the first session is still undisposed. You may have to restart the editor or Discord to fix it.
Discord thinks the same app is trying to initialize twice, because the first session never stopped.
even when i try to run the game with discord closed its the same error
Are you testing in the editor in playmode?
yes
Have you tried restarting the editor?
couple of times
can you recommend me any good beginners tutorials for scripting, so i can learn and understand what the things do?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks
any other ideas?
whenever i move with my object normally, it says the y position keeps changing even though it isnt. do you know any way to fix this?
ok
the end is being cut off because the field is too narrow
but sometimes my jump doesnt work because i use this to figure out if im on the ground: grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
and for some reason because of that i cant jump sometimes
but with such a small number it shouldnt really matter
so then thats probably something else i did wrong
You should raise the starting point of the raycast a bit
Change this from "Center" to "Pivot"
That will show you the actual position of the Player object
ok ill do that
I think your raycast is sometimes starting inside or below the ground
ok
This logic would make sense for when your origin is at the center of the player
for a raycast starting at the bottom of the player, I'd do something more like
but then the raycast doesnt need to be half the players height and just a little bit
transform.position + Vector3.up * 0.1f for the starting point and 0.2f for the range
ok
Right!
Also, to help catch this kind of problem, you can use Debug.DrawLine or Debug.DrawRay
Debug.DrawRay(transform.position, Vector3.down * (playerHeight * 0.5f + 0.2f));
This will draw a line for one frame that shows what the raycast is doing
Debug.DrawLine(transform.position, transform.position + Vector3.down * (playerHeight * 0.5f + 0.2f));
an equivalent use of DrawLine
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
is there any issue with this code? my jump isnt working
it jumps sometimes but sometimes just wont respond
if (Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
make sure that your code is actually running with a Debug.Log
That's a telltale sign that you're trying to handle input in FixedUpdate
Thanks
Hey folks, I'm trying to create a game similar to "Mushroom wars". I don't know how to select building and sending troops to another building in better way. Could you suggest smth regarding it?
nobody knows what mushroom wars is, and this question is extremely vague. If you have some specific code problem you want help with, feel free to share that.
Build.framework.js.gz:10 RuntimeError: null function or function signature mismatch
at Image_set_sprite_mC0C248340BA27AAEE56855A3FAFA0D8CA12956DE (Build.wasm.gz:0x45f0f0)
at U3CLoadImageU3Ed__1_MoveNext_m6D83251DF156589F38D586F36FAF7346023AA45F (Build.wasm.gz:0x9b6b7b)
at SetupCoroutine_InvokeMoveNext_m72FC77384CAC3133B6EE650E0581D055B34B2F5F (Build.wasm.gz:0x5d2f9c)
attempted to load a texture from url
not sure what this error means
currently using a webgl build
so the exception seems a bit obfuscated with (Build.wasm.gz:numbers)
that's why i dont get it
playerCamera is already a Transform; there is no need to do playerCamera.transform.position. basically, you're saying transform.transform.position. the rayCast variable as a float is confusing because it's a distance, no?
true yeah
to help with the first part, search: unity how to set parent. that's an easy one . . .
I know how to set parent
I'm saying how to get access to the object im looking at
and setting that one a parent specfically
sure, well, do you know what this line does? hit.collider.CompareTag() . . .
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hello, I am trying to get the object when the cursor hovers over it. I tried void OnPointerEnter(PointerEventData eventData):
when using eventData.hovered[eventData.hovered.Count - 1], I am worry about the size of list could affect the game, just assuming, not sure if it can be an issue
Is there another method to achieve the goal? or methods to optimize the hovered list, if it is a problem I should worry about. Thanks
can someone help me to detect wheter i am walking or in idle https://gdl.space/etowecogex.cpp
I would doubt you should worry about its performance.
You can also check if the object is being hovered with the mouse methods or by checking if the cursor is within the object's bounds
Not sure what you mean. You should try to explain it better.
I tried using thread.sleep and I clearly don't understand how it works. How do I achieve a sleep in this part of my code without all of my code sleeping? ```
void Update()
{
Thread.Sleep(1000);
inputHandler.playerScore = inputHandler.playerScore + idleBonus;
Debug.Log("Idle score added");
}
You don't.
You can never block the main thread. That freezes your entire game.
Ever. Don't try to do it.
now, there are alternatives!
this lets you run an enumerator method over many frames
But you will never be able to make Update "wait"
Coroutines have entered the chat!
A very very common error I see is:
void Update() {
int x = 1;
StartCoroutine(Wait());
x = 2; // this runs immediately
}
IEnumerator Wait() {
yield return new WaitForSeconds(1f);
}
You'll simply start a coroutine that waits 1 second, then does nothing
Read the documentation.
It explains how to use them.
private void LookInCameraDirection()
{
if (!characterController.velocity.AlmostZero())
{
//// Vector Solution working
//Vector3 characterV = characterTransform.transform.eulerAngles;
//Vector3 cinemachineCameraV = cinemachineCamera.transform.eulerAngles;
//Vector3 rotation = new Vector3(characterV.z, cinemachineCameraV.y, characterV.z);
//characterTransform.transform.eulerAngles = Vector3.RotateTowards(characterV, rotation, 360f, 360f);
//Quaternion Solution
Quaternion characterQ = characterTransform.transform.rotation;
Quaternion cinemachineCameraQ = cinemachineCamera.transform.rotation;
Quaternion rotation = Quaternion.RotateTowards(characterQ, cinemachineCameraQ, 360f * Time.deltaTime);
characterTransform.transform.rotation = rotation;
}
}```
Im trying to rotate the character according to the cameras y axis..
The commented vector solution works, but has polarity inversion problems..
Thus im trying to make the quaternion stuff work.. it works fine, but its not just rotating in y-axis, but all 3 axis.. how can I fix that?
hi, the eneny is replaying the anim constantly and jittering please help, tysm
yes it checks if the ray hit an item with the "name of it" in the brackets
I wrote the code im familiar with what I wrote in there the only part I dont get is getting access to the objects components with the tag item without direvctly dragging and dropping that item in the inspector
Would I say like object = object.GetComponent<RigidBody>();
no.
RigidBody rb = object.GetComponent<RigidBody>();
is there anything bad with running a code that will error a lot inside a try
yes, try catch is very expensive
is there something cheap where i can ignore errors then
i asked because you access the object in order to check its tag, meaning you already have access to the hit object. check the docs for RaycastHit, it tells you everything you have access to from a raycast . . .
NO. Errors should never be ignored
So do that and don't be lazy
that's normal. that's life . . .
in this case, you don't need to because hit, a RaycastHit has a rigidbody property . . .
Thread.Sleep freezes the entire application.
In C#, if you want to wait some time before executing something, you'll have to create an async Task, which uses await Task.Delay(milliseconds).
However, in Unity, it's much better to use an IEnumerator with WaitForSeconds(seconds).
Yeah I got some help with that. Thread.Sleep was a bad idea. Currently trying to get WaitForSeconds to work. Having some issues atm
You can post your code to get further assistance
{
inputHandler.playerScore = inputHandler.playerScore + idleBonus;
Debug.Log("Idle score added");
yield return new WaitForSeconds(1f);
} ```
``` void Update()
{
StartCoroutine(scoreAdd());
Debug.Log("IdleScoreAdded");
}```
What this code does is:
Idle score added
IdleScoreAdded
- wait for 1 second
that makes absolutely no sense
You usually call the methods in PascalCase, so it would be AddScore
And your WaitForSeconds is returned after the actual code logic, which makes your Coroutine do nothing after waiting for 1 second
Idk man I set it up how the docs did
Send me the docs which provided this code
They had wait at the bottom https://docs.unity3d.com/Manual/Coroutines.html
Because it's a for loop, which has a possibility to execute once more after waiting for seconds
did you not notice how theirs is inside a loop ?
And back to the docs we go. I didn't notice that. Going to have to learn about for loops now too
Shouldn't you already know about for loops at this point?
On day three? Probably not
Then you should not learn Coroutines yet
Consider learning basic C# syntax first
And yet this is the code that I need to make my current endeavor work. I'm not looking for criticism on what I'm choosing to learn. I'm looking for help concerning what I'm trying to learn. Tutorial hell wasn't helpful.
So I'm picking up on what information I need along the way
doesn't hit store data whether the ray is hitting?
"tutorial hell"?
Tutorial Hell is a state of perpetual learning, often marked by the consumption of one tutorial after another without putting acquired knowledge into practice.
in your code, you need to check if the collider is null before trying to access it. it can't store data if it did not hit anything . . .
hit is a struct so it cannot be null however the properties of it will be if nothing is hit
hit is a struct, so it can never be null . . .
uh oh
haha, i hear an echo . . .
Why do I need to check if its null? I've never done this befoore can't I just use an else statement ?
if the collider of hit is null, then nothing was hit. you cannot compare the tag of nothing . . .
best to use charachtercontroler movement or rigidbody movement?
depends on your game and the type of movement you want . . .
Got it. Anyway, I don't remember criticising you, as you have mentioned in your previous response. What I'm trying to say is that it's not the best way to learn hard things without knowing the basics, which is what is definitely going to help you on your way.
a survival game not really any special movement just the basics running jumping crouching
Yeah is that not what hit.collider does? It checks if the ray is hitting something then if it is checks if the name inside of the () in comparetag
and if it is not hitting anything its null?
and you cannot check the name of something that is null
It checks if the ray is hitting something. If not, the hit.collider is null.
yeah exactly
so this is where im lost now because that makes sense to me why do I have to check if hit.collider == null
Because hit's type is RaycastHit, which is a struct and cannot thus be null
you do if(Physics.Raycast(out var hit)) to check if you hit something
when you do hit.collider.CompareTag("Item"), you are accessing collider (assuming it exists), but if it is null, you will receive a null reference exception . . .
without collider there will be no hit
yes I understand that part
but how do I access an object that has the tag item
rigidbody and collider inside of that if statement
like this https://gdl.space/qezayuteva.cs
What do you mean?
hitinfo has a transform member
you already have access to it. hit.collider access the collider of the hit object. check the docs. RaycastHit has many properties of the hit object you can access . . .
ohh I see
So it gets access to whatever is in there basedd off what its hitting
so I could do something like Rigidbody rb = GetComponent<RigidBody>(); Then do rb.isKinematic = true; then repeat for collider?
I just checked the docs. You are right that it can be null. But it is easier to check the return of the Raycast method than do a null check. So there is no reason to acces hit information if you didn't hit anything
if you wrap the Raycast in an if statement it returns a bool. if true, the ray hit a collider . . .
is this right?
that would be inside the if hit.collider
a bool is easier to check than a null reference . . .
no, this will get theRigidbody of the GameObject this script is attached to . . .
dangit
I have never mentioned that you should check it
again, did you look at the RaycastHit docs?
mulitple times
if (Physics.Raycast)
hit.rigidbody
did you look/read the properties?
How could you have not seen the rigidbody property then?
I think I was looking at something different then
may have been looking at physics thisi entire time
Yeah I was looking at physics.raycast before
it's not that hard to tell if you're looking at the correct docs. the name of the class or struct is in bold at the top . . .
how, we mentioned RaycastHit docs multiple times . . .
Thought it was the same thing at first
Want to set itemContainer as a parent of object that has tag "Item" that my raycast hit
itemContainer.SetParent(hit.transform);
Then want to set Items position equal to itemContainers position
hit.transform.position = itemContainer.transform.position;
then want to make the item I picked up isKinematic
hit.rigidbody.isKinematic = true;
Then make it so its now isTrigger
hit.collider.isTrigger = true;
hey guys, I have a small question about audio in unity
basically, I want my weapon to constantly make sound depending on the amount of charge it has (more charge means higher pitch)
what'd be the correct way to implement it?
I see thank you
But could I have it so When I Input.GetKeyDown(KeyCode.E)){ && hit.collider or not possible ?
because it looks like hit.collider would set this to the case anytime its hit or am I mistaken?
What does it mean?
set a min/max range for the pitch. update the pitch when the value of charge is changed . . .
when charge is at its lowest the pitch can be normal or a lesser (min) value. when the charge is full, the pitch will be at the highest (max) value . . .
If I want it so this code hit. whatever is only ran if I click e and my raj is hitting couldn't I use something like if (hit.collider.Compare.Tag("Item") && Input.GetKeyDown(KeyCode.E)) { then put the code you put inside so it will only run if I click e and my ray is hitting the object
float pitch = Mathf.Clamp(charge * something, minPitch, maxPitch);
they'd need to remap the values. charge and pitch most likely have different min/max values . . .
Well, the code I've provided was originally meant to be put inside of your condition, yes
It would be better to check for inputs before the Raycast. So you would write
if(Input.GetKeyDown(KeyCode.E) && Physics.Raycast(..))
okay I understand thank you and just to confirm it gets access of the object its hitting right not the object that the scripts attatched to?
why would that be?
Should I always check for inputs before another condition is met is that good practice?
!code
Surely. It will also access the object the script is attached to if that's what it's hitting
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
because there is no need for the raycast unless you press something. And inputs are easier to check
using hit will access the GameObject that interesected the raycast . . .
makes sense yeah
https://gdl.space/hutusaxoya.cpp
ayone can help me why my cinemachine camera is not moving properly with where i am watching while when i have only regular camera it works perfect
I suppose, they both should be in percent
So 0f - 1f
What am I missing here? I'm trying to learn coroutines and I think I'm missing something.
{
StartCoroutine(scoreAdd());
}```
``` IEnumerator scoreAdd()
{
for(;;)
{
inputHandler.playerScore = inputHandler.playerScore + idleBonus;
Debug.Log("Idle score added");
yield return new WaitForSeconds(1f);
}
}```
No, you should usually check for the inputs first
Looks like a valid coroutine that increases the score every second. What's wrong?
should? yes. realistically? probably not 😔 . . .
It just does nothing. I have nothing in my score or in my debug logs
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
We need to see the context in which you wrote these methods
Is the object active? Can you verify that Start is called?
Is there an exception to this rule
is the script attached to a GameObject? is the GameObject active in the hierarchy? does idleBonus have a value (to add)? can we see the whole script?
Uh oops. Start isn't called
Yes.
if (checkForInputs)
{
if (Input.GetKeyDown(KeyCode.Space)) // ...
}
Is the Start method ever called?
I fixed it. I am an idiot. I had start at the bottom.
"At the bottom"? What does it mean?
It doesn't matter whether you have a Unity Message at the top or bottom of the script. It's called anyway
At like line 50 beneath all my other code
So what?
This is exactly why sashok told you this #💻┃code-beginner message
huh? Start is automatically called when the GameObject is first active. you don't manually call it . . .
the order you declare methods in is completely irrelevant
Now I'm interested how you have fixed it by, as you say, changing the position of the method
smells like an inner local function to me
I had deleted start. I put it back in at some point and got Assets\IdleButton.cs(40,10): warning CS8321: The local function 'Start' is declared but never used
Moved it back up where it belong and the error went away and my logs started showing that the coroutine was working. Just made a silly mistake.
Syntax
note that the line number of Start is completely irrelevant
It ended up getting lumped in with something else though
it's the fact that you declared it inside of a method that caused a problem
that's definitely a local function . . .
Yeah I know.
that's not a silly mistake, but a lack of knowledge and structure of your code. your formatting is complicating the issue . . .
take the time to make sure your code format, variables, etc., are correct. it makes code flow and readability much easier . . .
hello
I have a question about the Factory pattern
If I can make an abstract factory for my factories
does that mean that I can make an Abstract FActory for any kind of factory in the project?
Or is that too much abstraction?
You can do a lot of weird things. But it usually doesn't make sense
So it may be better to make abstract factories for each "thing" in my project, for example
An abstract Events factory, then an abstract Cards factory, etc...
a factory to do what, exactly
I'm making a card game, so I need to create a lot of cards and a lot of Events, which are objects that encompass behaviour
If you benefit from this abstraction you can do it. You don't need to do it just because it is a pattern
what am I even supposed to do with an abstract card factory
Create any card with it
why can't I just instantiate a card prefab and then pass it some data?
Because that would need a huge switch case, and I want to avoid it
Tbh, the factory would probably do that
no, you just pass the card some data, and it configures itself based on that data
I haven't ever really felt the urge to use the factory pattern
But then I'd need to tell apart which card data is being passed, hence a switch statement
it's what I"m currently doing ni my code
but it's bloaty and I don't like it
Same with my Events system
the card data should include things like the name, the image, and what text to display on the card
so the card (a MonoBehaviour that's part of a prefab) can configure itself when given the card data
(gotta scram!)
Ok, I'm gonna think about what you said and see if I can make something simple in my project!
Thanks for the reply!
Based on what I've been learning recently, with cards, Scriptable Objects seem to be the perfect solution. There are a bunch of YouTube SO vids that deal specifically with cards.
My biggest beef is finding a nice way to compose card effects
I think that cards are not the problem
How do you mean?
Cause I turned all my card effects into Events
But creating the Events is being a problem
It's beggining to turn into an ultimate spaghetti
What do you mean by effects?
So I'm having to rethink things
behaviour
Card does X when played, Y at start of turn
Ah okay. I get what you mean.
I'm trying to separate my code nicely, but it gets more and mroe compelx the more I try haha
I don't think events are necessary if honest.
You could create a seperate public script that 'manages' the cards effects (maybe a singleton, not sure), and every time you play a card you just call a relevant method inside of said script to modify values (ie, if it's an 'attack' card, send damage, hit chance, crit chance etc. to AttackCard() method and have that modify the player/enemy stats?
Anyone have any idea why the items tagged item are not picking up https://gdl.space/omojagakal.cs
I was doing that but when it came to queuing effects, this became hell
Hence, turning actions into objecst
It's called the Command Pattern ( I just read about it yday lol)
log what is actually being hit, your raycast is likely not hitting what you think it is
Debug the tag before the comparetag check
And the object name
Ah okay, not familiar with that one if honest. I'm something of a fan of Singleton Pattern. It soothes my brain. lol.
How could I do that?
log
Debug.Log(item?);
People say don't worry too much about patterns, but damn, just using one pattern made one part of my code suddenly so easy to write and read
I'd say the more you know the better
log the object that was hit
You've got 3 'checks' in there, raycast, collision and keypress, so you need to debug each one to see which one is 'missing'
Debug.Log(hit);?
The learn.unity site would have taught how to log values....
But hit is the struct containing information you need. Access values from it
That is the START
.tag as well as .name
Debug.Log("I have hit xxx using raycast/collision/keypress") kind of thing.
technically just logging the collider would log its name. so just the collider and tag
True
I did say 'kind of thing' 😉
What the hell kinda raycast is this.
One where you are moving the origin point and direction
nothing wrong here
Looks like you've got a line gizmo rendering and it's rendering a new line everytime the ray is fired (every frame?)
just has a longer duration on ray
So yeah, that looks like it's working as it should to me.
I thought that was the length of the ray?
rayCast is the duration... rayCast is not a good name for that variable
ray legnth is dir * length
there is no length param (only on raycast)
you wrote transform.forward
that is a direction
It is transform.forward in your call
Sorry, was thinking of the actual raycast coding, not the drawline.
ah
im trying to play a death animation after player collides w enemy. https://gdl.space/ufoyozorof.cs this is my code. rn it just keeps on going infinitely rather than only once.
the death animation going on infinitely
rather than switching back to the idle one
btw i created my own animationSprite class
rather than using animator
💀
It's not logging
turn off loop on the animation?
just a guess
then either your raycast is not hitting anything or you put the log inside the inner if statement
im not using animation or animators tho
like i created my own class
which object has this script
player
you put the log inside the inner if statement
cause its using its forward not the camera
its using the camera no?
don't do that since that if is clearly not ending up as true and you are trying to figure out why
put the raycast direction from camera.forward
oh dangit
u right
I had the transform.forward and it was going off my player not my camera
big oopsie
also this should be
Debug.DrawRay(playerCamera.transform.position, playerCamera.transform.forward * rayCast, Color.red);
that name is atrocious though
call it rayLength or some shit..
dock what?
the game and scene view
just drag the tab
to the scene?
you will see it will snap
move it around
now my layout is busted
my ray is still cooked
did you change the rotation to be camera forwarD?
or is it still transform.forward
show updated script
so u didnt change it for raycast?
wym
and they didn't bother moving the log either
yeah the gizmos is still wrong
I'm confused now.
what Transform did you drag into playerCamera
no i mean in the field of inspector
What did I drag into the transform in the inspector ?
look at lines 21 and 22. notice how the direction of your DrawRay and your actual Raycast are different
wouldn't the Debug at least be correct forward ? Assuming playerCamera was actually linked to camera
fixed it
i thought it was butter 🧈
ya, i thought that too
turns out Reset Layouts reverted it back to the layout i had when i opened my project
dont see how origin could fix the direction but alr lol
would I use an else if for a drop or another if you guys think
sorry, come again?
me?
you would store the item you grabbed which you did not do
Depends on the behaviour you want
ohh its item_pickup.
a typical drop
also hit.rigidbody.isKinematic = true; is a NullRef waiting to happen
sorry i didnt have context.. i udnerstand now
No such thing.
Click a second time and drop? Press a specific key and drop? One of the many other ways?
Gonna have E for pickup and G for drop
oh fr?
but I thought only If I click E
If press G and currently holding, drop held item
🤷♂️
yes u need to check if it has a rigidbody first
and then check if that rigidbody is kinematic
at least the ones with "item" tag
well its also possible to click E when ur looking at something w/o a rigidbody
yeah that's fine because I have three conditions if !itemHeldd, InputE and hit.collider no?
colliders can exist w/o rigidbodies
you should lookup a simple pickup video
you'll see..
you need to store the item you grabbed into a reference so you can do stuff with it
Well in theory its easy just disable collider when u pickup and make it kinematic so it doesn't fall out of your hands and when you have itemheld true and input G renable rigidybody and collider no?
not all colliders are rigidbodies capishe?
Ah yes that is a problem
aren't they seperate?
they are seperate components
agree'd
you only need colliders for raycast
CachedInteractable is my variable i store..
Yes but i still want to disable gravity when I pick it up so it doesn't fall out of my hands no?
if you grabbablle items have rigidbodies you can just store it as a Rigidbody
didn't I do that in the script via hit.collider.rigidbody
thats assuming your Item even has a rigidbody
or do I have to instialize it somewhere
if it doesnt it will null ref
u can't reference your HIT outside the scope of ur raycast
also ur not storing it
how you plan on enabling kinematic back to false on that same object ?
When ItemHeld && Input G renable collider so doesn't fall through map and rigidbody so it can fall to ground
doesnt answer what i wrote
rigidbody.kinimatic = false?
and what is rigidbody ?
a component attatched to the object im holding
i dont think its clicking
which item is that
nope
Gold bar
how does your script know thats whats ur holding
yeah
i think its clicking now
no one saying its not possible obv is possible
oh
you just need an extra variable..
you have to understand how to store references to things
is X possible
Yes
RIGIDBODYIPICKEDUP = theRigidbodyYOuHit;
how to store a reference?
the same way you are storing the other ones
make 1 like all these
With an = sign
make a variable for it first
so I create another variable for each of the components
Rigidbody should be fine
just 1 ^
Rigidbody StoredRigidbody;
StoredRigidbody = rigidbodyYouHitDuringYourRaycast;
Just the one they keep saying over and over
Rigidbody heldItem;
Hello, i'm making a 2d platformer game and i'm having some issues with resolution. When i build the game and play normally without changing the resolution, the guns work fine. However if i change the resolution the game doesnt accept any inputs to the guns anymore
u dont need it to be serialized
inside the if statement?
or start
its not going be touched in the inspector
that doesnt make sense
you are using it as a storage bin
it would be when u hit it with ur raycast + push E
or w/e
when u ray hits the thingy... store the thingy
sure
lmao
but what information am I updating when that code runs
is it a bool, a numerical value
you made a field for rigidbody, the type you will store is the rigidbody
when you find said item, you assign it to the itemHeld
^ your gonna be manipulating the RIgidbody's parameters.. soo u store a rigidbody 
huh ? whats itemEquip
sorry meant itemcontainer
if (Input.GetKey(KeyCode.E) && hit.collider.CompareTag("Item"))
{
Debug.Log(hit);
// Store the Rigidbody of the hit item
itemRigidbody = hit.rigidbody;
// Set item as child of itemContainer and adjust its properties
hit.transform.SetParent(itemContainer.transform);
hit.transform.position = itemContainer.transform.position;
itemRigidbody.isKinematic = true;
hit.collider.isTrigger = true;
itemHeld = true;
}```
no?
if they all have rigidbodies the code will work for all of em
oh
your only gonna be holding 1 at a time yes?
we are taking its rigidbody and storing it in there so i can later drop it?
/ Store the Rigidbody of the hit item
itemRigidbody = hit.rigidbody;
if(!itemRigidbody) return 😏
when u Drop it however you do.. u can just use itemRigidbody.isKinematic = back to false
drop it
set itemHeld back to false..
etc
well you will
and store it like we did with rb
but you already have rigidbody to grab collider from
^ magic
myrigidbody.TryGetComponent(out Collider col)
you can grab a collider through a rigidbody?
u can attempt to grab anything from anything
that is some magic indeed
why not = instead of try?
rb = Getcomponent<BoxCollider>();
if ur rigidbody also has an Image Component u can say myRigidbody.GetComponent<Image>();
why would you assign it to anything
and grab an image from it
true
if(myrigidbody.TryGetComponent(out Collider col))
col.isTrigger = false;
so does tryGetComponent just grab it and store it
yes if its found it stores it in a local var
itemRigidbody = hit.rigidbody; this part of ur code can error... say u hit a collider that doesn't have a rigidbody..
you'd need to check if it actually has one before u assign it..
w/ a TryGet it does it all in 1 step
Tryget sounds a bit confusing lol I've only used Get
// Try to get the Rigidbody component from the hit object
if (hit.transform.TryGetComponent<Rigidbody>(out itemRigidbody))
{
like so
if theres a rigidbody it automatically assigns it to itemRigidbody if theres not. it does nothing
So that would be inside the if Input blablablah ?
that goes when you try to assign it

what does the out repersent
its a way to return values from a method without changing the actual return method type
so you can return multuple values and still reutrn 1 value from method
In this case bool is method return type and out gets the component found if any
i have a Rigidbody reference called itemRigidbody .. it just assigns it to that variable
I see
it just denotes that itemRigidbody is being passed as an output parameter
so basically just says if its not null slap it onto itemrigidbody the component?
exactly..
and if it doesn't have one don't do anything
yup
that way u wont get errors when ur trying to set isKinematic on a collider that didnt have a rigidbody inthe first place
or something close to that
what is this part then col.isTrigger = false;?
do note, out doesn't care if its there or not. You can technically asign it a null
its trygetcomponent that prevents that
it gets assigned to Null if theres no component to get correct?
or ignores it?
does it or it skips the whole operation if its fals on tryget
liek say i already had a reference in there.. and i tryget on a object w/o one
would it reset it to null.. or leave it how it was?
if im not mistaken it will not touch the field at all
i ask b/c i manually set it to null
ahh awesome.. i did right then
yeah u have to explicitly assign it
like this?*
you ever get imposter syndrom but then actually solve something and you suddenly dont feel so imposter 😛
way too low in the function
oh
u should do it before u do any of this stuff
That log should be BEFORE the if statement, as box said a long time ago.
You may not need it anymore, but it is not super useful there
Just something to know for the future
and instead of hit.rigidbody.. u can just use storedRB.isKinematic etc
also the type here is already implied as being Rigidbody through the variable you are assigning to out, you dont need the <Rigidbody>
before the physicsraycast or the other if?
how long have u been workin in unity? how many lessons have you done?
okay I'll remove it
Well it cannot be before the raycast of course, because that is what generates the hit.
Before the comparetag
almost two weeks now
oh okay.. i was just curious
yep lol still fairly new just setting a goal to make a game once a week
as long as I'm learning something new yk
storeRB = hit.rigidbody defeats the whole point of doing a tryget lol
oh?
the out automatically assigns it
peep this for a second..
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, rayCast))
{
if (Input.GetKey(KeyCode.E) && hit.collider.CompareTag("Item"))
{
Debug.Log(hit);
// Try to get the Rigidbody component from the hit object
if (hit.transform.TryGetComponent<Rigidbody>(out storedRb))
{
// Get the Collider component from the stored Rigidbody
storedCollider = storedRb.GetComponent<Collider>();
// Set item as child of itemContainer and adjust its properties
hit.transform.SetParent(itemContainer.transform);
hit.transform.position = itemContainer.transform.position;
storedRb.isKinematic = true;
// Ensure the collider is retrieved and set its properties
if (storedCollider != null)
{
storedCollider.isTrigger = true;
}
itemHeld = true;
}
else
{
Debug.LogWarning("Hit object does not have a Rigidbody component.");
}
}
}```
ofc thats way more complicated than it even needs to be.. but my own example uses interfaces
that'd be even more confusing
we are assigning collider to rigidbody?
yeah but you said storedcollider = storeRb no?
this sets a collider to the Rigidbody's collider
it sets the left side to equal the right side
this = that; <--- this becomes the value of that
If you just store the hit, you will have access to both
^ big brain
yeah I know that part im confused how you can assign two different components to equal that
RaycastHit myStoredHit;
They used getcomponent
Both are rigidbody
get the collider from the rigidbody ^
2 weeks i figured you'd know what GetComponent does pretty well
one of the first things i learned after Debugging ofc
we should be pushing this tbh
okay how are we getting a collider from a rigidbody if it doesn't even have a collider yet ?
it'd be so simple to store the hit and get everything you need from the hit
because we are getting it in the same line
if it doesn't have a collider this function would get skipped
so it isnt a problem
yeah but then if you want to directly work with a specific component you have to store it anyway or keep doing GetCompoennt
but we run getcomponents anyway..
idk. TryGets are way better.. but can they get implemented
thats teh question
but now everytime you gotta change something you have to run GetComponent
ok fair.. 🙌
If an object has multiple colliders, is there a way to know which is colliding?
we DUMPED alot of info on Nicholas
lol head imploded
yea, im hoping he can find a method that works for him
if theyre on separate gameobjects maybe
You can check the shape if they are different
I'm honestly very confused but understand the general sentiment of storing components using hit or tryGet
You can check some property of it like radius if they are different
ya, we didn't expect EVERYTHING to sink in.. but even if u pick up a little knowledge here and there.. thats progress
So it’s better to find a way around it than attach multiple colliders to one game object?
Generally you want them to be child objects that handle their own collision validation and inform the parent.
But it depends on what you are doing
just remember TryGet
is just GetComponent with an extra check for if(component == null) //dont store it or do stuff
true yeah and I would assume this is much more optimal than having to get a refrence to each object you pick up and all its compononents in the inspector via [SerializeField]
Create a child and give it its own collider?
what navarone just said is the general purpose of the info dump.
Yes, AND its own script
and the output would be the parameters which I could assign it to if its not null right
if u try to store a rigidbody.. you need to check if it even exists before using it...
tryget helps u avoid having extra if conditionals
to check if != null
in the tryGet yea the out is what can be assigned if its found

so what would in do
if out assigns it
you just plop in one of ur own variables
and it'll get assigned
you then have that variable to use all thruout ur script
what do you mean what would you do
no i mean like we use out variable name to assign it in the parameters
is there an In instead of out
would it take it away
if u dont want it anymore u just set it to null manually
there is a in keyword but its not for what you think
else { storedRB = null; }
makes more sense yeah
thats if u miss a raycast for example
out Type name makes a new local variable, unrelated to anything else
out existingName assigns it to an existing variable
^ heck yea
wouldn't that be bad though?
What?
the first one because you couldn't access it outside of that area?
That is the point of local variables. Why would that be bad?
It is good if you don't want to access it outside of there.
Bad if you DO want to
but if u wanted it to be accessible thru the entire script u'd use the existing variable.
its just choices
if its found " assign it this local variable so you can do stuff in the if statement valuating true"
you dont always need to assign a field if ur doing a one time thing
Sorry does local mean like within an if or an update how local are we talkin when we say local
maybe a health hit or something
yes the local would work with anything "underneath"
including if statement
but it wont work outside statement cause it will be null anyway
Within whatever scope you create it in
only within that if tho right
{ scope }
well yeah the whole point of the if is "i found this component, store it local var"
using it outside of if statement would not make sense
If you make it in the if, then yes
waht bout the else of that if
makes sense yeah I was wondering if it was the entire function or just the if
technically it would be accessible throughout the rest of the scope that the if statement is in, not just the if statement's own scope
ya,,, thats what i was thinking
oh
Yeah, I was trying to think of how to explain that and kept restarting. That is better
it will just be worthless to use cause it could be empty
ur IDE will let u know when u try
so the entire method that its located in
Not necessarily
anything underneath it like i said
The outer scope holding the if, if you write it in the condition
i frequently use TryGetComponent as a guard clause like
public void Foo()
{
if(!TryGetComponent(out Bar bar)
return;
bar.DoStuff();
}
heheh..
I should do this more, it would clean up my TryGet
Round [2]! Fight
so this would work then void MrPotato()
{
if (can < bigCan)
{
vector3 potato;
}
potato = null?
}
I like early return pattern anyway no idea why i didn't think of that lol
no because you are trying to use the potato variable outside of the scope it was declared in. also Vector3 cannot be null anyway
early return is life . . .
but its below b ut inside the method still
value types cannot be null
only game objects and things that exist makes sense
that doesn't matter. it was declared in a more restrictive scope. you can only use a variable within the scope it was declared in
like components too
void MyMethod()
{
if (x == null)
{
if (Raycast(out Foo bar)
{
}
< accessible here
}
< not here
}
so only within its curly braces
in which it was declared, yes
void MrPotato()
{
Vector3 potato = Vector3.zero;
if (can < bigCan)
{
potato = new Vector3(1, 1, 1);
}
else
{
potato = Vector3.zero;
}
}```
if u declare potato before the if.. u can use it in the if and the else
and even after the else
..bigCan huh 🤨
makes sense yeah
if(potatoes < needed) // famine
I want to make a game out of this genius concept
navarone will hit me with a copyright strike
most likely
nah I use blender
hey! me too
I'll make it a sparkly potato and turn the specular up
the only potato i want
did u make that
naa i wish
is that perpetual energy potato?
I think they use that in space don't they because they don't have power there like as a power supply of sorts
glados as a potatoe
ahhh portal references
actually let me not topic lol
never played 😄 im aware of the cake
thats literal blasphemy
they have a special circle in hell for you xD
😈
if not one of the best puzzle games made
what's portal lol?
as a gamedev you have tooo..
reminds me of minecraft a bit based off the video
what
it has squares on the walls
funny
i made a clone of it.. thats close enuff
You zomies all know skibidi and minecraft/roblox ?
you have confused me beyond belief
oh i think its two oo's
how can i pass more than 1 argument using an slider ui?
bro called me an energetic dog 🤣
Zoomie. Zoomer. Gen Z. Younger generation
he meant Zoomer i believe 😛
its a nickname for generation Z
ohh
you can't in the UnityEvent, but you can work around that requirement
ohh this is osmething i need to know 👀
I don't use social media besides youtube but I saw moist critical react to skibidi toilet. I feel bad for the up and coming generation im 19 so i experinced peek gaming aka mario galaxy & pokemon platnium
i gamed in black and white >8)
I am so sad right now, that either of those games are considered peak gaming
I wonder what gamin was like back then fr
do like me.. and ignore that it was said
galaxy n pokemon? or skibidi
Ignore what, didn't see anything
I mean they compared portal to minecraft.. we're doomed
Glider is a Macintosh game written by John Calhoun. The first version of the game was released in 1989. The main task is simply to avoid a collision with the floor or obstacles such as furniture. A puzzle element has been added to the game in the form of switches that control air vents, lighting, and even enemies.
Please like this video and sub...
reminds me of those flash games I used to play on my school computer as a kid
I was jokin T_T
lol.. they were maxing out their RAM on those games
excuse me best game was
Programming for old consoles is particularly interesting.
what about Number Munchers?
ok thanks
Lots of very severe design constraints.
didn't they make a show for that on netflix
thats what made them EPIC imo
designing with constraints always ends up awesome
hey does anyone no how to temp stop an animation im changing my font for my game and it has resizing animations and is a little buggy but i wanna keep but wanna stop temp anyone know?
is there a netflix show for this?
my younger sister loves it
unless its something diff
yeah it was one
idk if they remade it or playing the OG
hi guys what is the error in this code? :
TextMeshPro txt = Layer1.GetComponentsInChildren<TextMeshPro>();
i already got
using TMPro;
its TMP_Text
its still not working
or
"It's not working" is not helpful
Read the error.
thats not right is it?
TextMeshPro and TextMeshProUGUI are the concrete component types.
TMP_Text is a parent of both
Ah, box got it. ComponentS
That returns an array
ohhh, i honestly didnt know TextMeshPro was valid
TextMeshPro is the non-ui tmp text
that's the 3d text version . . .
thanks, noted it
what does the [] represent
its an array
An array
an array . . .
[TripleKill]
how to compare types including parents
you mean like is ?
something like this
protected static bool isObject(Type type)
{
Type t = type.BaseType;
while (t != null)
{
if (t.Equals(typeof(UnityEngine.Object))) return true;
t = t.BaseType;
}
return false;
}
Usually with is
yeah but it only checks for exact type
yeah i wasnt sure if isassignablefrom works
so any array type would match with system.array and everything would match system.object
that way of compatibility
you are talking about comparing types of an object. OP asked about just comparing types
how can i serialise a scriptable object?
can you actually explain what specifically you are trying to accomplish so that we can reduce this confusion about what the answer to your question is
in what way? just to drag a reference in the inspector, or do you want to write its data to disk/send over network?
write to disk
create a class or struct to hold the data that you want to write to disk and serialize that. then just save/load that data to/from the SO at runtime
just realised for my specific setup i can just use an enum so thats fine
don't actually need to serialise the whole thing
i don't see how that is relevant to serializing a scriptable object 🤔
i wanted to serialise a character or level for a replay system, but i can just serialise an enum and link the two that way
I also have a little problem of my own. I found this code that uses the new input system to detect when a collider is clicked. The issue is I don't know how to make the script detect which collider it is clicking. It only detects that a collider was clicked.
private void Awake()
{
_mainCamera = Camera.main;
}
public void OnClick(InputAction.CallbackContext context)
{
if (!context.started) return;
var rayHit = Physics2D.GetRayIntersection(_mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue()));
if (!rayHit.collider) return;
{
playerScore = playerScore + scoreToAdd;
scoreText.text = playerScore.ToString();
Debug.Log("Point added");
}
Debug.Log("Clicked");
}```
I'm assuming it has something to do with the line if (!rayHit.collider) return;
that is the check to see if nothing was hit. the rayHit variable contains info on what was hit and if the code after that line is running that means something was hit
So forgive my ignorance here, but how does it know that it's trying to detect a collider? I don't see anything in there that has anything to do with colliders
don't just blindly copy code. actually look at what it does and research methods used
That's what I'm trying to do. That's why I'm asking...
My character's feet are sliding on the ground behind the body, what could it be. I'm making a Ragdoll player and using a configurable joint for that.
And so they vanish once more like a ghost in the fog
they are probably just afraid of having a better solution suggested. they once told me they don't want to describe what they are actually trying to accomplish "because your xy questions always lead to different solution which im not able to execute"
#1202574086115557446 for ML Agents related stuff
Have you profiled?
my bad I didn't know there was a channel for that
Hey all, just following the tutorial on Junior Programming and all is well except when it came to the step of changing the player controls to make the vehicle I am working on actually turn rather than just slide left and right. I have checked my code and this line provided in the example seems to work for them but does nothing for me. Anything I am missing?
This is the line that seems to do nothing.
transform.Rotate(Vector3.up, Time.deltaTime * turnSpeed * horizontalInput);
whats ur turn speed?
if the code is the same, its probably that ur setup is a bit different than theres
Was set to 0, tried changing it in the code but maybe need to change in Unity rather?
check inspector values, ur hierarchy, and the components on the objcts
yes, change it in unity inspector
the inspector value overwritse the coded value
i have a tilemap of pellet rule tiles. how would i access the gameobject for each pellet in code?
Yep that did it, it was working but since turn speed was zero it wasnt moving. Thank you thank you!
Quick follow up question though, why does it seem in the tutorial they are hard coding these values? They clearly set turnSpeed = 45.0f but you are right they then change the inspector value as well. Whats the point in coding that value then?
Feels like I'm abusing this chat but
When should I do a factory pattern as an interface vs an abstract class?
I have no idea how to predict if I i'll need to use properties in my factories later on
Plus, should I make my factory methods static?
That seems so much easier
Everywhere I look people are saying to do one or the other, it' been very confusing
if u hard code the value it'll be that value in the inspector
once u save it tho... and change it the 2nd time. that value in the inspector wont change on its own
when you try to convert a variable from one type to another and it is not valid
note this doesnt apply to changing it during runtime
if u change the variable in ur code it will change in the inspector (at runtime)
hi. im still having a lot of trouble making limited air control for my character controller using the move(); method
see #854851968446365696 for what to include when asking for help
its a pretty complicated system for CC.. like i said yesterday.. its gonna take a while to get it working the way u want
https://www.spawncampgames.com/paste/?serve=code_870 heres my CC, it uses momentum damping for jumping and stuff... It can be something u can look at but I can't be answering questions about it 😄 as its complicated and took 6 months to make
the key is groundMovement + airMovement <-- pass the result of both vectors into the Move() function
and ur calculating them differently.. (airMovment has a slower speed) both are being dampened (trying to get to zero).. soo if u were running and jump and then release the keys.. you still move forward a bit.. until the dampen slows u down enough to stop moving forward (airMovement gets to 0)
Is there any Vector3 of an object with the (transform.right, transform.up, transform.forward) axis?
how can 1 vector be 3 different directions?
explain what you are trying to accomplish
Oh you're right that would be a matrix 😄
I wanna move into camera direction.. I could provide you with the code..
use transform.TransformDirection to convert your input from local space to world space relative to the transfor you call that method on
Camera.main.transform.forward;
foo.forward
foo.TransformDirection(Vector3.forward)
these are equivalent!
could you elaborate?
Im working with a rigid body component and was trying to use playerRigidBody.linearVelocity = movementVelocity;
as in, pushing W makes you move forwards and pushing D makes you move right?
figure out what your frame of reference is and use its transform to turn your movement input into a world-space direction
exactly.. I got my camera orbitting me in 3rd person..
and I wanna do exactly what you said.