#💻┃code-beginner
1 messages · Page 487 of 1
sample terrain on raycast
If I want to have two game objects use the same script but react to different tags how can I do that? I'm guessing I could replace "Asteroid" with a variable but I don't know how to make that variable adjustable in the inspector
quick question
once i get really big numbers it looks like this
not good for a text box cuz nobody knows what that is
I'm trying to complete my assignment for lesson 2 (throwing food at stampede. I've followed the lesson as best as I can, but for some reason, the animals keep spawning too swift and too close to one another . Here is the code for the spawn manager for better understanding.
this is just scientific notation, did you try actually displaying it in a text object in game?
!code this is really a pain to read, get yourself an ide and proper formatting. plus also no one knows what lesson 2 is. if you want them to spawn less often then increase the interval
📃 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.
is there like a setting to disable scientific notation
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
you can choose any way for it to be displayed, assuming you're using ToString on some float. but also, you shouldnt really be working with such large numbers if you're using floats
you could just expose a string to the inspector and use that in the CompareTag function. there are also ways to expose the dropdown list for selecting a tag with this editor code
https://docs.unity3d.com/ScriptReference/EditorGUI.TagField.html
would it not show on integers?
i could just switch to them in that case right
🤷♂️ i dont know exactly what you're trying to achieve. i linked you a way to display numbers using whatever format you want
ok thank you
Ohhh!!! Thank you!
Btw it comes handy the other way, if you need to type a large number in your code, you can do this for example var largeFloat = 1000e8f; instead of counting zeroes
@teal viper Hello again, let's continue about my problem? I'm not English person and I only learn it now. So, look at this code. What I need to make with PlayerData class? What I need to change in Values class? And also, do I need change my SaveSystem class?
Values class: https://hastebin.com/share/motinuzoka.csharp, PlayerData class: https://hastebin.com/share/ifisafizew.csharp, SaveSystem class: https://hastebin.com/share/edogurapih.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Oh I got resolution... I was need to watch the tutorial about loading and save system to the end...
NVM, fixed it!
My cursor doesn't show when I open the menu in my 3D Game. This has been happening to other games of mine too, I cannot seem to fix it! Any little help would be greatly appreciated.
At the end I fixed it in 20 minutes today after work with fresh mind.. Basically I created a method in my PlayerHealth Script and inside that method I was changing the variable to false, but I was activating that method in my SpawnManager, for some reason that was not working. Now I just instead of doing that creted the method inside the SpawnManager and worked. Must have been some kind of process order that was happening .
using Unity.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]float jumpForce;
[SerializeField] private float speed;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private LayerMask wallLayer;
private Rigidbody2D body;
private Animator anim;
private BoxCollider2D box;
private bool isGrounded()
{
RaycastHit2D hit = Physics2D.BoxCast(box.bounds.center, box.bounds.size, 0f, Vector2.down, 0.1f, groundLayer);
return hit.collider != null;
}
private bool onWall()
{
RaycastHit2D hit = Physics2D.BoxCast(box.bounds.center, box.bounds.size, 0f, new Vector2(transform.localScale.x, 0), 0.1f, wallLayer);
return hit.collider != null;
}
private void Awake()
{
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
box = GetComponent<BoxCollider2D>();
}
private void Update()
{
float horizontal = Input.GetAxis("Horizontal");
body.velocity = new Vector2(horizontal*speed, body.velocity.y);
if (horizontal > 0)
{
transform.localScale = new Vector3(-40,40,1);
}
else if (horizontal < 0)
{
transform.localScale = new Vector3(40,40,1);
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded())
{
Jump();
}
anim.SetBool("Run", body.velocity.x != 0);
anim.SetBool("isGrounded", isGrounded());
print(onWall());
}
private void Jump()
{
body.velocity = new Vector2(body.velocity.x, jumpForce);
anim.SetTrigger("Jump");
}
private void OnCollisionEnter2D (Collision2D collision)
{
}
}
for my player whenever it touches a wall it only returns true for a few seconds and then returns false is there something wrong with the code?
There's a big hint on the documentation of BoxCast if you go read it
Actually, maybe that only applies to 3D physics of shape casts, but usually those will not detect colliders inside of the cast.
Let me give you a better way to do this though and that is by invoking a collider directly instead of doing a casting query.
its detecting the ground though the only issue is for the wall
Trying to figure out what overload you'reusing here. What's those 2 parameters before the last signifying
where
Ah, ok you're swapping the sprite scale for direction I see
Looks fine, the only thing I can think of is that the boxcast isn't detecting the collider inside of the cast
i see
whenever i give the wall a rigidbody it will work but idk why it wont work normally ;p
Like I was saying, instead of querying a specific shape, I like to create multiple colliders and just invoke those. (It's easier to visually see and debug)
Collider for the bottom, collider on the side for wall
ah i see i see, im still learning this stuff so just refering to yt and its working for the person 
Can you debug that the scale x isn't changing
could be some other issues, but debug why it failed in the first place
So, I want to have an obstacle, it's a rectangle, on top of it I want to have ground layer, and sides would have wallLayer, how do I do that?
Is there any way to change GameObject layer at runtime?
gameobject.layer, no?
Yes, by assigning its layer property
The obstacle has to be made out of 6 3D planes with different layers, put in a single empty object
It's 2D
i tried, it doesnt do anything like tag property
I have a class named unit and for some reason every time I try to accsess or change something about it I get the NullRefrence error but the thing is I Debugged it and I know for affact that the unit itself and its variables are not null so I dont know why does it happen
The SetHUD method is example for when it gives me the NullRefrence error
but when I debugged unit.unitName it gave me the right name
so unit.unitName is not null for a fact
what line is 14? Debug it and check if its not null
where do u see line 14?
i mean 17
line 42 stats manager?
line 17 isn't null
Other script gives you error, maybe its related?
idk why does it happen
the thing is
every time I use / change any information for the class Unit I get a null refrence error
even though its not null for a fact
ok nevermind
I accutaly GOT IT
fnialy
did you debug what specifically is null?
I was on it for hours yesterday
The thing is
the player was a unit class and not a class that inheriet from unit
and unit is an abstract class
that makes no sense in relation to this error
Found out fix (hopefully permament), is that it doesn't matter if wallcheck checks for wall layer or groundlayer
The plane is a 3D object
It should work if you assign it correctly
Okay
Is there a reason you have a wall and ground as different layers?
What does this mean?
So, you player was of type Unit
I wondered the same. I think they fixed it by accident and just associate a random solution to it now
Especially considering they said unit is abstract, you cant make an instance of it. Meaning itd be a compile error way before a null reference error
I still want to know how they've come to this conclusion
Not for now
hey is there something like a transform.forward but using rigidbody.velocity ?
But will probably become useful later
so my velocity gets applied to the local rotation of the object
oh ok ty.
my player keeps moving even after i let go of the a or d keys i understand i can use getaxis horizontal and it all works well but i need a and d for the key rebindings i plan to do later
Since rigibody.velocity is a Vector3 in global space, you can multiply the added value with tranform.forward to change it to local
This happens, because velocity can be called constant, which means the object is moved forward every frame once the velocity is assigned once (e.g. in the Start method)
so what should i do instead call movement in void start()?
You might want to use Rigidbody.MovePosition instead
rb.velocity = transform.forward * new Vector3(rb.velocity.x, rb.velocity.y, pitchSpeed * playerControls.flying.Pitch.ReadValue<float>() * -1);
like this? bc it keeps spitting me out an error and idk how to fix it
would that stil be smooth?
You cannot multiply vectors, since the *(Vector3, Vector3) operator doesn't exist
Use Vector3.Scale instead
You cant multiply vector by vector. If you want to rotate a vector, you would do it like Quaternion * vector (or the other way around I always forget the order)
isnt the order of a multiplication irrelavant
It affects the performance
But there is no quaternion used in the code
The thing is that Quaternion has a multiplication operator on a Vector3, but it doesn't work othwerise, therefore, the Quaternion has to come first
public static Vector3 operator *(Quaternion rotation, Vector3 point);
Yes
This depends what you're multiplying. This is a whole math concept you'd learn in university. But here specifically in unity, its defined with Quaternion*Vector and not Vector*Quaternion
Fixed formatting
smth like this ?
MovePosition takes neither the current position nor Time.deltaTime. Only speed is required
i got this but my player just teleports really fasy to the right
Read the first part of my response
without transform.position it gives an error saying cannot complicitly convert float to unitysmth
You now need to convert it to "unitysmth"
Also it seems that you have to use Time.fixedDeltaTime (or Time.deltaTime) with MovePosition anyway. My bad, sorry for that
Just make sure it's put in FixedUpdate
how do i convert?
By multiplying it with Vector3.one
``` what can i do so my rotation doesnt reset to 0 without input and goes farther the longer i hold the input
rotation is a Quaternion not an Euler angle
what do you mean what does it change about it?
look at your code, it is complete nonsense.
you are taking Quaternion values and putting them into a Vector3 which you are then trying to evaluate as if they were Euler angles.
You need to rethink your approach
i dont understand i mean it rotates as it should basicly it just doesnt stay on the rotation it should
there is no way that code comes even close to working
A video tells me nothing. But if you dont believe me, go and do some research on the difference between values held as a Quaternion and those held as Euler angles
wdym like for something that doesnt work it looks like it works just fine
The only reason it "works" is because of playerControls.flying.ReadValue<float>() * RotationSpeed. Quaternion values are in range -1 to 1, whatever rotation you're getting is basically ~0 + value_you_read
Once there is no input the only value that's left if the quaternion value from your rotation, again in range -1 to 1
!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.
does it work if i use the transform.Rotate()function?
Everything will work as long as you use it correctly
transform.Rotate(0, playerControls.flying.Yaw.ReadValue<float>() * RotationSpeed, 0); did i use it Correctly?
this is my "typewriter effect" script which i use to display text, i have it set up to send an event action when the text is complete, but im not sure how to go about using those events to interact with other scripts and tell them when to swap to the next line of text
and would the 0s reset the rotation on other axis?
There's only two ways to find out. Either try it out or read the documentation to learn how to use something
ok i think it works pretty correct
is this maxfilecount now a constant?
no
how do i make it one?
what did google say?
i get google also helps but this channel is also for getting help
⚠️ Before Posting
🔍Search the internet for your question! 🔍
⠀+ Use the API Scripting Reference and User Manual.
⠀+ This troubleshooting site for commonly posted issues.
and your question is easily answered by a 10 second google search
do you have any errors?
no but i dont get errors if i put this and this has nothing to do with being a constant just give a yes or no please
if you do not have errors after writing that code using the const keyword which google would have told you is used to create a constant, then clearly you did it correctly.
as for whatever this other screenshot is for, i don't know what you are asking there
that is not how to use a compile constraint
Is it a good idea to start from Unity starter controllers and customize it for our needs ? (like the third person controller)
if that is how you want to start, then sure
just to confirm, are you actually trying to point out here that you aren't seeing any errors in your code even if you write incorrect code? because if that is the case then you need to get your !IDE configured 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
is there something wrong with my question
How to change text of the child
You need the specific component
What do you mean?
I have gameObject, it's not specific component...
Of course it's a specific component
GameObject doesn't have a "text" property
Look at the line of code right above yours
Everything important is on Components
does it make a difference if I finish writing .transform or not?
You should try to understand what the code actually does
.transform gets the Transform component of whatever you call it on
I don't really understand the question to be honest
But my code does not error in any case
This code certainly has an error
Look at the red underline
Logic based on gameobject names feels so wrong
it is typically a bad idea
Two problems with this:
- the text object is likely a child of this object, not the same object
- it's very unlikely you're using Text which is the legacy component. Most likely it's TMP_Text
I'd recommend using enums in this case, or making a base class Toggle and child classes like MusicToggle, SFXToggle, or making an IToggle interface with Toggle function. Maybe for a single-person project it is somehow manageable to operate on strings, but still error prone. Doing this while working in a team is a no no. Still, even for solo proj it's best to learn correct practices instead of getting bad habits
Please don't
Abstracting everything into a Toggle just limits your code in the future, and generally it solves nothing
And instead of an enum you're better off using an constant if you are trying to avoid magic strings. Regardless I would wrap this in a method that takes a boolean instead, and call the change from there. It would be a decent place to call for the component, and the boolean can indicate if something is on/off
whether to abstract this out or not is a matter of project design, but it is always better than checking gameObjects name
Name? Are you referring to the Find method being used?
The correct solution there is to just not use that at all
Oh, we're looking at two completely different things
there's thousands of solutions for this, he picked the worst ;p
they're talking about this: <#💻┃code-beginner message>
My Discord didn't scroll all the way up, I thought it was about setting the text
Right, I see what you mean. I assume this is a toggle visual and I agree you might as well create a prefab/reusable component for this
I feel like that code is wrong, though. I get the idea this person is trying to define multiple toggles, only varying by their gameobject name. That's not a good idea
yeah, a toggle should have only one method and one boolean field, nothing more. So inheritance is the proper approach here
optionally some notification mechanism, but SFXToggle should not even consider "am i being a MusicToggle?"
I am facing a very frustating problem since 2+ months. It has slowed down my development and made my experience a misery. Please help with few details I can give.
- Problem is simple - whenever I make any changes in my Codebase, the Visual Studio (and VS Code) intellisense stop recognizing Unity SDK and may be dotNET SDK.
- It happens after Unity rebuilds on any Code changes.
- If I reopen Visual Studio, I get autocomplete and other intellisense functionalities. But as as Unity build happens for any change, it even does not recognize "List" and starts throwing error in IDE.
I know it is not exactly Unity. But I am stumped for months. 😦
i dont think .activate is a thing? unless im wrong
there is .SetActive / .enabled? if you mean that
i dont even know if .activate is correct
oh .SetActive?
yeah
I don't think that's even proper code, do you have errors by any chance?
yall know why my presets in starter assests show 9 instead of 12?
i dont know i didnt save yet
hi! im really new to unity and i'm trying to make some velocity based movement, but it really doesn't work. no errors. just jitters all over the place.
use AddForce or directly set the velocity
alright, i'll try that.
Hm, well some issues I see is using "activate" - thats not real, use .SetActive (As was said), or .enabled for components, but that isn't what you are doing.
Second issue, GameObject.allthestuffneededforhardmode won't really exist either
Banana would you like me to provide some sample code to show you how it would be done?
thanks a bunch! it worked!
im having trouble with this:
it shows 9 instead of 12.. i keep restarting and the same thing happens to me. Yall know why?
do not cross post
cross post?
Send in multiple channels I believe
post the same question in multiple channels
yes you did #💻┃unity-talk message
You sent this in #💻┃unity-talk
you should have left it in #💻┃unity-talk and deleted it from here as it's not a code question
it wont let me say uh
Yeah agreed with the message above, anyway, the solution: There is meant to be 9, I think an older version has 12, just use them as 9, not 12
it looks like this (im polish so i dont really know what sample means but i think it means just show)
Yeah no that won't work
It basically means provide you with some code to learn off of
no cause the other 3 are nessesary for movement
ohh ok then yeah
Well, if you are certain it has them in it, then reimport the samples and see if anything is missing
Alright, 1 second
ok
ty
np
it no work😭
Search for an older version that has the 12, try find the specific version
Or update the package if it's not updated
But I assume it is
Weird, have you tried actually testing movement without the 3?
Also @brittle kelp
// These are just setup as normal bools would be inside a class, i'm just lazy to make a class right now
public bool IsAllowedToDoIt = true;
public bool IsAllowedToDoItConfirmed = true; // Just made 2 because you had 2 to show you how that would work
public List<GameObject> ObjectsToEnable = new List<GameObject>(); // You can put your gameobjects into this list in inspector
public void EnableObjectWithConditions()
{
if (IsAllowedToDoIt && IsAllowedToDoItConfirmed)
{
foreach (GameObject obj in ObjectsToEnable)
{
obj.SetActive(true);
}
}
}
thank you
This is how the code should be formatted ^
Np, don't just copy it and stuff, learn off of it as well so you know what to do next time
yeah it doesnt work ( also its a vr game if you dont know)
Hm, i just looked and my VR game has all 12
What version of the samples are you on?
No, the actual version of the sample
dark did you have some particular learning method for becoming proficient at 10 languages
Hm, try downgrading to 2.5.4 (What I use)
how?
No idea, you'll have to figure that out on your own, you could search up how to downgrade unity packages
Trial and error mainly
ok
Well for most people it does, but it really depends on the person
If it takes a while for you, you just need to be patient in your learning
true
if only i was a faster learner
Well either way, I wouldn't rush it if I were you, just take your time, you'll get the hang of it
guys i made a game and every time u swipe it should appear 2 platforms so u can jump on it but everytime i swipe it dosent work and it dosent add any platform why?
If you are asking questions about code, post the code that is meant to be doing it, I can't help right now, as I'm heading to bed, but if nobody helps you, DM me and i'll try help
ightt
using UnityEngine;
public class SwipePlatformSpawner : MonoBehaviour
{
public GameObject platformPrefab;
public float spawnDistance = 10f;
private Vector2 startTouchPosition;
private bool isSwiping;
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
startTouchPosition = touch.position;
isSwiping = true;
}
else if (touch.phase == TouchPhase.Ended)
{
Vector2 endTouchPosition = touch.position;
if (isSwiping && IsSwipeUp(startTouchPosition, endTouchPosition))
{
SpawnPlatform();
}
isSwiping = false;
}
}
}
private bool IsSwipeUp(Vector2 start, Vector2 end)
{
float swipeDistanceY = end.y - start.y;
float swipeDistanceX = Mathf.Abs(end.x - start.x);
return swipeDistanceY > 100f && swipeDistanceY > swipeDistanceX;
}
private void SpawnPlatform()
{
Vector3 spawnPosition = transform.position + new Vector3(spawnDistance, 0, 0);
if (platformPrefab != null)
{
Instantiate(platformPrefab, spawnPosition, Quaternion.identity);
}
else
{
Debug.LogWarning("Platform prefab is not assigned.");
}
}
}
i told chat gpt i understand some of code i asked him cause idk how to type on yt
Well some issues I see (Just before I go to bed, this is my last message, you'd have to ask another if what I say doesn't work): Possibly because you are checking the value for 100 distance, which is a lot I believe, so maybe try put that down and test again, put it at like 1, see if it works, if it does, keep going up until you get a good value.
Also add some debugs in your code at points to see where your code ends, then say where it ends (What doesn't execute) so other people can help you fix it easier.
debug to check if the input is working
TYSMMM YOU HELPED ME FIX IT!!!!!
post !code properly (read the bot message about Large 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.
No problem
{
if (distance.magnitude < maxDistance)
{
//checks if distance magnitude is less than max distance then it finds a fraction and multiplies the normalized version of force by this fraction and negates it
force = -force.normalized * 10 * distance.magnitude / maxDistance;
//adds force to the rigidbody velocity
rb.velocity = force;
}
else
{
//as distance is greater than max distance, the force is equal to max force and this is added to rigidbody velocity instead
force = -force.normalized * 10;
rb.velocity = force;
}
}```
for some reason the raycast in the if statement doesnt work and im not sure why
how do you know its not working
the debug.log isnt returning in the console
and when i press on the mouse button and the ball is on the ground, it doesnt do anything
i dont see any debug.log
i did it earlier
show us where you put it
in a different if statement with only the raycast statement
{
if (distance.magnitude < maxDistance)
{
//checks if distance magnitude is less than max distance then it finds a fraction and multiplies the normalized version of force by this fraction and negates it
force = -force.normalized * 10 * distance.magnitude / maxDistance;
//adds force to the rigidbody velocity
rb.velocity = force;
}
else
{
//as distance is greater than max distance, the force is equal to max force and this is added to rigidbody velocity instead
force = -force.normalized * 10;
rb.velocity = force;
}
}
if (Physics.Raycast(transform.position, Vector2.down, 10f))
{
Debug.Log("True");
}```
Never remove debug logs when you're asking for help. We need to know wheat you tried and how.
yes and yes
the radius of my ball is 0.5
and i have it set to 10
the raycast set to 10 distance
and it does the thing i want it to do without the raycast
i think you should visualise the raycast with debug.DrawRay
You dont even need DrawRay anymore, the Physics Debugger now shows all casts
is there a raycast2d?
are you in 2d?
yes Physics2D.Raycast
then yes use raycast2D
i am behind the times
i had this issue before as well
i forgot 2d physics is a thing too
thank you for your help
easy mistake
i need to generate my tile based world infinitely as my player walks outward, so would it be best to have a world generation script on the player, or have the script on each tile, so they replicate themselves?
basicly: more scripts = bad?
have it on neither probably
neither. world generation should not be the responsibility of the player, nor should it be the responsibility of individual tiles. you should have a separate object that handles world generation
so just place it on an empty game object in my scene?
yeah
Another little bit help if ya don't mind, how to do like close the game?
The object is its force close if we touch that yellow
(Also, is my code are wrong?
(This should be last help
i said do the beginner courses, not repost your question here. and get your !IDE configured too
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Alright, thanks.
I need a piece of ground to follow the player around on the xz plane (so it's always underneath the player) so I don't have to have an insanely huge collider in this huge flat open space I'm making, but setting the position every frame is bound to mess up collision between the player and the ground. I'm not sure how to approach this...
well - one question - what's wrong with the "insanely huge collider"
second - I think actually setting the position of the collider every physics frame won't cause many issues either.
e.g.
Transform target;
Rigidbody myRB;
void FixedUpdate() {
Vector3 oldPos = myRB.position;
Vector3 newPos = target.position;
newPos.y = oldPos.y;
myRB.position = newPos;
}```
This will be fine tbh
1 big collider wont cause performance issues if thats what you are worried about
now if the mesh has a ton of tri's and vert's then thats a whole different issue
but if it is just a box you will be okay
even if it's like 10k by 10k?
yes
its only 4 vert's well should be if you are in 2d, 8 if you are in 3d
and if its static, its even less on performance
I guess, I'll just make a big ol floor collider then xD
This ain't code but I am not sure where to ask:
Does this setting thingy work? How should I use it? I changed it to 256 and built again and my textures ain't 256 😛
(I did a clean build, still no 256 😛 )
use id:browse to find relevant channels for your questions instead of posting in an unrelated channel.
but what are you expecting to happen with that setting
all images bigger than 256 to be resized to 256 🤔
and how have you confirmed that the textures have not been imported with a max size of 256x256
it also appears you have not even applied the overrides
so i have made the game in unity but for some reason the device is heating up for no reason art is very minimal and also code is also not that much i am getting the 120 fps on phone and 800 fps on pc but im not sure why my android device is heating up any idea?
It's heating up because it's doing stuff
any advice or something that can help me to make that heating issues less
profile your game and optimize any hotspots so that your device has to do less stuff to make the game happen
Or limit your framerate
will try these stuff
This is why phones usually limit the framerate to 30 or 60 fps
i've dragged a rigidbody2d into here, and whenever i click play the rigidbody gets unnasigned and it gives me this error
do you have a GetComponent in the Start method?
u arent draggin in a prefab reference are you?
currently just following a youtube tutorial, and this is the code i have so far
probably this then @solemn cedar
im dragging it in like this
the rigidbody must be in the scene
what is Bird ? can u show the hierachy of this script and the bird rigidbody?
soo everythings on Bird im guessing
the rigid body and script yes
do you have this script on the camera perhaps?
the camera is normal
what
its working now
all of a sudden
i literally just dragged it in like before
i dont know why the slot would become empty when u start..
but since its on the same gameobject
you could do:
private Rigidbody2D myRB;
myRB = GetComponent<Rigidbody2D>();
}```
to assign it via the script
ah you probably dragged it when in playmode last time
ohh 😭
you can make your screen a different colour when in playmode to avoid this
how do i do this?
it'll save me from future headaches
i think its under edit > preferences > editor? or something else not sure exactly
somewhere here?
thank you
surpised this isn't default tinted..
i actually prefer the lightly grey tint
was really helpful at first tho to have a color (purple ftw)
ysssir
{
Debug.Log("working");
yield return new WaitForSeconds(2);
Debug.Log("working1");
while (inMainSequence)
{
var carbonPush = Instantiate(Carbon, UICan.transform);
carbonPush.transform.SetAsFirstSibling();
carbonPush.GetComponent<Rigidbody2D>().AddForce(Random.insideUnitCircle.normalized * carbonSpeed, ForceMode2D.Impulse);
yield return new WaitForSeconds(carbonSpawnRate);
}
}``` for some reason working is being called but working 1 isn't and i dont know why
Is the object that starts this coroutine being destroyed or deactivated
yes but the object with the coroutine isn't being destroyed
What object did you call StartCoroutine on
an object that gets destroyed just after calling start coroutine
So then the coroutine is stopped when that object is destroyed
Call StartCoroutine on an object that will actually stick around
StartCoroutine is called on a behaviour
that behaviour is running the coroutine
It doesn't matter where the function that return IEnumerator is, since that's not the object running it
They are dependent on the object they are attached to
Try starting a Coroutine using another MonoBehaviour, and you won't be able to stop it from your current script
I've seen in some components that you have to click a flag/boolean to get access to some settings. How can something like that be done to my own scripts?
write a custom inspector for it or use something like Naughty Attributes or Odin Inspector which both have attributes that can add that functionality
Ah ok, so it's not something I can do by default (without writing a custom inspector)?
Correct
Gotcha, ty
There are editor extensions that make it easier to do it: https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
Oh, this begs the question actually. What do you guys prefer? Naughty Attributes or Odin Inspector?
Odin is very heavy, but more feature rich
Naughty is more lightweight
most of my projects don't get far enough to ever actually need Odin features
Odin's serializer is also famously slow
Hmmm. Sounds like I might start with Naughty then
My player doesnt turn left or right for some reason and I don't know why, could anybody help? https://pastebin.com/sUEwBZKY
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.
well for one you're constructing a new Quaternion which is wrong
besides that, you should put some logs and see what is happening inside if statements
Quternions do not go above 1, so -90 for example is nonsense angle
oooh
work euler angles instead
alright, thank you!
how do I do this? is it something like "euler(0,0,180)" ?
Quaternion has a function to create a Euler angle
Quaternion.Euler(xyz)
Thank you!!!
is there an event for when the editor saves?
do you mean the actual editor or the scene?
either works for waht im trying to do
there is this for overall editor but looks to me more of an override type of situation than an event
https://docs.unity3d.com/ScriptReference/Editor-saveChangesMessage.html
thank you! what about entering play mode?
there is prob something in here https://docs.unity3d.com/ScriptReference/EditorApplication.html
Quaternion.Euler is what you want.
Sorry - had some discord lag
didn't see the newer messages
I already got the answer but thanks 👍
oh lol
I gettin double the help, this is sick 🙏
NEVERMIND 
I need to use a TryCatch to move files, but I also need to move the files asynchronously- anyone know what I can do? I'm at a loss.
Are you getting an error or something?
Yeah- TryCatch cannot be used in coroutines
- You should clarify that you're using a coroutine I. The initial question. I expected you using async await.
- Share the actual error.
- You could try extracting the file loading part(including the try catch) into a separate method that is called from the coroutoutine.
- Putting file loading in a coroutine is not gonna help, unless the file loading is async as well. Maybe share your code as well.
im having Sprite Issues out of all things
when i place the sprite down the actual visual and the info box are just off set
What is the "info box"
1: What's async await??
2: NotSupportedException: Coroutines cannot catch exceptions.
3: This blocks the main thread.
4: The main thread isn't blocked when I move files from a coroutine.
your anchors are set to the left, maybe you want center?
you see that is what i thought, but that dosent chang a thing
Did you change the positions after changing the anchors
yes
Was there an actual question?
I only see 2 screenshots and some sentences that don't really explain much without context.
kinda made it better, but that because i took the 2x2 version and just made it bigger
questing is how does one shift it up & over by .5
can you not just drag the UI element where you want?
Shift what? The grid? The icon? Is it even an icon? Is it part of the canvas ui?
Too many variables that we don't know...
i dont have a UI
...the Assest
What asset??
i dont get how that was difficult
wdym??
the black box with a crappy pickaxe on it
yhea its hard to see with all the words
You need to start talking in full sentences. Explain what you're trying to do. Explain your setup. Explain the issue. Read #854851968446365696 on how to ask questions correctly. We don't need to be playing the guessing game here.
you are the only one want to play a guesing game
Okay, that's better, but what is it? Is it a UI image? A sprite renderer? A quad mesh?
im done with you
Great. Then I guess you can solve the issue yourself.
it would be easier then getting YOUR "help"
wdym no UI? also dilch was asking for more information, you were instead giving loose information of which we have to guess
if you have a canvas you should have some UI elements
also this isnt a code question, best continue in #📲┃ui-ux
well your game object has a RectTransform not a normal Transform which indicates its UI
if you are using a rect transform, you must have a canvas
or some UI element
I want to find all AudioSources in a scene, then store them in an array. Anyone have any good pointers? I'm looking this up but I don't see anything on it.
If you're instantiating these audio sources via code, it would be a good idea to add them to the array that point as well.
ouu thank you !!
im not but that is a good point
i proly have it and not using it right then
i looked up how to change the anchor point but i guess i might've not need it
well you are using it since you were afflicting the recttransform
i dont think UI works without it
Can anybody assist in making my character's jumping more smooth?
I have a rigid body character and Im using this to jump:
playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
The jump works, but it's too immediate/not smooth. I want it to behave more floaty and smooth like when jumping with a character controller component
you can lower gravity to make it more floaty, not sure what you mean by more smooth
the main way usually is using a different gravity going downwards than going up
im prolly using it wrong them, or at least in a unattended way
gravity is always going downwards 😅
gravity isnt the issue. The character falls at a good rate and that is fine. It's that the character reaches the max height of the jump too fast. It's like the impulse teleports them to the max jump height, rather than make it a slower transition. Does that make sense?
Can you record a video of what it looks like?
yes, will do
so try lowering gravity like was said?
to make it not so fast?
forcemode inpulse shouldnt teleport your character instantly, it only pulses your jumpforce
but yes do what dilch said, im curious
that looks normal, nvm just read your text
red is using character controller and is what I want blue to jump like (blue is using rigid body). Perhaps you all are right about gravity, but I play with it and it doesnt work like red
show your rigidbody settings
and what is your jump force
are you perhaps calling your function in Update()?
that doesnt really matter much anyway since its an Impulse, shouldnt give results like this
The force that you apply with impulse translates to velocity almost 1 to 1 with mass of 1. So you're applying a velocity of 500m/s to it.
Ah,it has mass of 10. Didn't notice
In this case it's something like 50 m/s
Enough to to move 50 meters/units in one second if ignoring gravity.
I changed jump force to 100, player mass to 1, and kept gravity at 15. It still jumps too fast. Am I missing something you are saying?
I am using fixed update
jump force should not be that high
That's even worse than before. Now it's 100 m/s.
Also share the code. Are you applying that force wry frame or something?
is anything in your code messing with velocity or are you ever slowing your character down in some way?
!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.
can show the full code
probably the GetButton, try deleting that part
You should not have KeyDown in FixedUpdate btw
but that wouldnt affect the jump behavior, just when it is triggered?
Button/KeyDown is a one frame event it would be hard to always get it on the physics loop, does it sometimes miss the jump ? the GetButton is probably not making you feel the jank as much, still it should be in update
I havent had issues with input, but I have seen your advice and planned on moving the getinput into update method
but right now I just cant figure out the actual jump. It just happens so fast. I dont know if my gravity is too low, force is too high, etc
they told you already you should not have such high force
1 or 2 mass is ok. Jump force too high
The velocity applying is also weird to be honest.
But the main issue is probably the force and gravity combo.
Applying 0 velocity on y would basically negate the jumping velocity on the next fixed update.
yup that should be rigidbody.velocity.y inside the Vector3
Which could explain why it's stopping abruptly despite moving so fast.
OMG YOU GOT IT
Thank you all so much!
I was so focused on the jump and not my other movement code
{
return Directions.DefaultIfEmpty(None).FirstOrDefault(direction => direction == vector2Int);
}```
So if I understand this correctly, FirstOrDefault() is a lambda expression where each direction in Directions is returned if it matches the function argument? What is DefaultIfEmpty(None) mean here?
I can't seem to get the visioncone to reveal stuff in the fog of war.. i have been messing with this for hours.. The 1st photo is sceneview.. the 2nd is sceneview in playmode.
not each - just the first one
DefaultIfEmpty(None) means return whatever None is if Directions is an empty collection
None is presumably some variable defined elsewhere in the file
do you even need that DefaultIfEmpty, when you have FirstOrDefault?
Yeah 'None' in this case is basically Vector2Int.zero. I want to remove the DefaultIfEmpty because its impossible for the Directions list to be empty
but I wanted to understand it before I did that
thanks
Yeah you can remove the DefaultIfEmpty
Yeah FirstOrDefault will also return default if the collection IS empty, which is also equivalent to Vector2Int.zero
I am trying to make a pixleated look for my game using a render texture, but any movement is like drawing on the camera and it stays
not a code question, but it sounds like your camera's clear flags may be incorrect
oopsy, I will look into it thanks
What is the actual question?
Is it something along the lines of "how do I implement a dialogue system"?
That is not a question
It's a statement
you're getting way ahead of yourself. Just start with something simple like detecting when the player walks near the NPC and presses a button. You have to work up from the basics before you get to the whole system
If you're looking for how to do the whole system, find a tutorial
Question implies asking something and has a question mark at the end.
None of your messages actually ask something.
What about dialogue trees
The answer is 42
Please learn to convey your thoughts correctly. Ask "How do I implement xyz?", instead of "I want xyz." Make it easier for people to understand you and you'll get proper answers.
That is the answer to the ultimate question of life, the universe, and everything, which of course is not known in this universe. You did not ask a question, so we can only assume you wanted to ask a question that nobody knew
This feels wrong.
Cache the input action so that you don't need to find it every frame. Assuming there are no other issues.
Hey yo! I am trying to implement spawning 10 game objects at random times. I was able to get it working but they all spawned at the same random time. Can I add the random code to each car spawn, add it in a way to get each to spawn differently, or have 10 different scripts that spawns each car differently?
It was to large.
https://hastebin.com/share/olodapopev.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Like this?
InputAction Throttle;
private void Start()
{
inputActions.Enable();
Throttle = inputActions.FindAction("Throttle");
}
// Update is called once per frame
void Update()
{
float forwardVelocity = Throttle.ReadValue<float>();
}
show the !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.
Thanks
Yes.
Though maybe pay attention to naming conventions.
Are single words not Sentence case?
What single words? And what's "sentence case"?
You mean Pascal case?
Throttle
And yes
It doesn't matter if it's a single word or not. In this case it should be came case, since it's a field.
Pascal case is only used for methods and properties within a class.
Anyone know why my ternary operator isn't working? (Yes, I will replace the magic numbers with actual variables soon.)
Nvm
Forgot the f lol
Hello, I am building a 3d L-System, I have the rules implemented and it all seems to work. The only problem is the right side, of the fractal seems to reset its Z position ONLY on the right side, even if I flip the code right/left it does the same. Heres a vid, heres what im aiming for, and heres the code ( one sec to get it all sent)
nice fractal
its not completeddddddddd
thankyou tho
im dumbfounded, whats funny is i can accidentally do the same thing to the other side, because i set z to zero unintentionally, so im trying to find where i did that on the other side but havent yet
can you screenshot the inspectors of Plant Base and Plant Base (1)
the only thing I can see is, you are pushing and popping the movingPoint position but not it's local position which will have been changed by the previous commands
trying this now
no change on the result
i feel like its a coincidence that the left side lines up the way it does. the first branch moves correctly, but not the Z value after for techincally both branches. the left branch just so happens to get the right calculation to match up, while the other side is offset by the same distance, which im guessin equals 0 for the right side.
which would tend to suggest that this
movingPoint.transform.localPosition = copy.transform.GetComponent<SkinnedMeshRenderer>().bounds.max * 1.01f;
is where the problem lies
i took out the 1.01
but yes, i think its a culprit, the bounds.max only gives a constant size for the y among all sticks ig, and the reason i have it like that is when i change the stick scale it will reach into the individual updated size and not the constant
change yur Debug.log to include the local position as well as the position
or so i would hope, its been a terrible work around
local on the right
it would be helpful to say that each stick is parented under another, organized in a way to pick of parts
i wish there was a clearcut way to track the top of a blenshape object. probably RecalculatingBounds() but it doesnt work on the mesh fsr.
I've had an idea, can you export your project as a .unitypackage and DM it to me so I can experiment
This sentence is to convey a sense of confusion and the sender's inability to solve this themself, as they have already tried and failed to. This sentence is overly verbose to comply with this Discord server's message posting rules, which prohibit single word messages, which would've likely been sufficient in this context.
you are missing the required parameter for the Unity method
Thx
next time read the docs
And does that not show you need a Collider parameter?
Oh turns out I accidentally had it in the OnTriggerEnter method- I really should post full code lol
I don't.
I know you don't but the docs show that you should
All they show is that the example happens to have one? It doesn't always require one
Output variables aren't always required though
that is not an output variable
You get what I mean
well, if there was an override that took no parameters the docs would reflect that
Your buildingManager is null. Most likely the BuildingManager.Instance isn't ready when Awake() is called
The execution order is probably different
okay
Use a property rather than assigning a field
private BuildingManager BuildingManager => BuildingManager.Instance;
Assuming you call this property after all Awake methods were fired (which you should), it will not be null.
Alternatively assign it in the Start method
yes assigning in start works
Can someone help me out on an error
There is a button, and when it is clicked it will change scenes, I tried rewriting the script, making another button, but there is always this error
might just be an editor warning not sure, try restarting unity / ignoring the error completely
Got it, thanks for the suggestions
Is the issue that this warning appears after clicking or does it appear regardless?
The warning means you have a Monobehaviour script attached somewhere of which the reference can no longer be found
Can for example happen when you change scenes and unload the scene that had it
This kind of warning generally appears when you modify a script when in play mode, ignore it
Thanks for the help
hey yall, quick question - so i'm developing a tracking state for a state machine enemy ai, however i'd like it so the ai goes as close to the player's original destination as it can before it goes to the alert state
currently this has a stopping distance, if i change it to something like (distance < 0.1f), the ai completely breaks in which i assume is a floating point error as it gets stuck in the tracking state
here is the code:
void Track()
{
enemy.indicator.material.color = Color.magenta;
enemy.navMeshAgent.destination = enemy.lastKnownPosition;
if (Vector3.Distance(enemy.transform.position,enemy.lastKnownPosition) <= enemy.navMeshAgent.stoppingDistance)
{
ToAlertState();
}
}
ah that didn't paste well, let me fix it
It happens after clicking a button, anyways is there like a solution to this, I tried restarting Unity, but it still appears
But I think I should just ignore it since it doesnt affect the gameplay
Like I said, big chance you are modifying/moving stuff around when you click the button and the reference no longer exists
You can press the warning to see what exactly is missing
should you not be checking the distance between the enemy position and the player position?
isn't it doing that within the Vector3.Distance function?
no

ah, I see what you mean. lastKownPosition is the destination required
yeah the lastKnownPosition is where the player was last seen
you only need to set that once
the code WORKS with the stopping distance just fine, but the ai stops a bit too early for my liking
well adjust your stopping distance. Stopping distance may not be what you think it means
adjusting the stopping distance will break the other part of my script, where the ai stops before hitting the player
Stopping distance does not mean WILL stop, it means CAN stop,
alrighty let me see
ah i found the problem
it was taking the stoppingdistance from the chase state
all i needed to do was to change the stoppingdistance when it entered the tracking state
all good now thanks 
lol, rubber ducking is a wonderful thing
This code is ment to spawn a lot of destinations for my ai to walk to, it is ment to attatch to the terrain but dosent, any ideas?
wdym by "meant to attach to the terrain"? because there's nothing in that code that indicates what you mean by that
also !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.
sorry
i got the code online and aparently its ment to spawn the destinations on the terrain
spawn the destinations on the terrain
are you for some reason assuming that this is supposed to make those instantiated objects children of the terrain object? because this code does not do that
no, just spawn them on the trrain
is there a easier way to place a lot of destinations?
have you actually put your scene camera near the objects and focus on them by double clicking to see if they actually are on the terrain? because the code should be doing that, but you may be too far from the objects to actually see it correctly (for example, you are so far from the selected object that the terrain appears to not be rendering at that location, though your screenshot is not very informative here)
no, all the location that have spawned have spawned in the sky( if that is what you ment)
How can I hide public method from inspector, for example, make not possible to specify it in UnityEvent?
At the same time, I need keep method public, because I wanna access it from other class.
[HideInSpector] attribute
just humor me. double click the object in the hierarchy and show what you see when the scene camera moves and adjusts its clipping planes. then also show the terrain object you've assigned to the terrain variable in the GridDestinationPlacer component (and ideally show the inspector for that object too)
that is for hiding serialized fields in the inspector. they were asking about hiding a public method from the selection menu for a UnityEvent
i believe the actual answer is "you can't" if the method is both public and matches the signature for the event. why would you need to anyway?
Well, for the safety, make not possible to call it from other part of project, only from code.
No side effects.
And good control.
There you go
does the terrain object have a parent?
yeah
yeah so that's why. i bet the parent isn't at 0,0,0 either
ideally the terrain object should be at 0,0,0 in world space yes
otherwise you need to convert the position from local space relative to the terrain to world space
is the terrain still at a location other than 0,0,0 in world space
i might have fixed it
Would anyone be able to help me with this?
this code 💀
thas what u code does.
if timer runs out.
spawn this
spawn that
spawn that
spawn that
etc
probably need to utilize a for loop
definitely need a loop
I see. I was trying to get each set of cars to spawn at a different random times. I will see if I can craft this into a for loop. Do I need a different script for each car group or just on to rule them all?
you can do it in this 1 script
is your idea spawn 1 wait 2 seconds spawn 1 wait 3 seconds spawn 1 wait 1.5 seconds?
a random time between each is what i understood
so just add the cars to an array/list loop through it then make random time
Yes a random time between each.
coroutines! cs IEnumerator SpawnCarsWithDelay() { foreach (GameObject car in cars) { SpawnCar(car); // Spawn car float delay = Random.Range(minSpawnTime, maxSpawnTime); //wait random time yield return new WaitForSeconds(delay); } }
Right now, they all spawn at the same random times.
Thanks for all the help. I will work on this with the suggestions.
Hello! I had a question regarding Unity/VScode. I installed VScode and chose it as my editing tool. Though when I try to open the project in VScode it shows me this
What have I missed? I tried following a tutorial
are you opening it by clicking the script in Unity?
What script.. (Im totally new to unity and havent gotten the hang of it yet😭 )
ill check this out
what don't you understand about this?
well what code are you trying to edit in vs code 🤔
if nothing then you shouldnt be opening vs code
I dont know, I was told to download VScode and now I tried following a tutorial. Me and my friend are working on a visual novel
I already have Unity installed and I need to work on the version that I have because my friend has the same version so we can share the projects with one another more easily
that is not telling you to install the unity editor. it is about the unity extension for vs code
oh.. My bad
does the word extension mean nothing to you?
I didnt see that I thought it just meant another version of unity
Ill install it
follow the entire vs code configuration guide: #💻┃code-beginner message
if you even want to pretend to be a dev you need to learn to read what's on the screen
I was just asking since Im new, I never said I wanted to be anything..
I will thankyou!
what do you think using unity is then?
I am just using it for a school project I didnt mean to offend you
Thanks again for everyone's help. I was able to get it running as intended.
don't ping people into your questions #📖┃code-of-conduct
ohh sorry didnt know that
it also helps to share code correctly. the bot linked how to share code correctly just a few messages before yours
You can post again or link to it
thnx
Can I get some help with making the two cursors in this script GamepadVirtualCursors to be able to drag objects in a 3d world. Just like in this script DragObject (updated with cleaner code) but with the New Input system and not the mouse. Please?
...how do I make OnMouseDown(), GetMouseAsWorldPoint(), and OnMouseDrag() accept the virtual cursors instead of the system mouse?
...problem is that I made followed a tutorial to make the gamepad cursors and it is a bit too good for me to understand.
is this the correct way of sharing the code?
did you follow the instructions from the bot? if yes, then yes.
it does not show up in the message, just links
yes because that is how linking code works
it also doesn't help that you are barely providing any information, just dropping two scripts and saying "help me make it work"
Alright, I was thinking that I was too wordy and using the wrong terms and thats why nobody wants to bother
does anyone know how to fully restart vscode? Everytime i delete it and redownload it, it opens where i left off. But i want to restart all over
but why
You can open windows/tabs back up from the View dropdown
how do I reach private Mouse virtualMouse;from another script?
You can't, it's private.
you can't access private members from another class . . .
Either make it a public field, create a public property, or a function that returns it.
yes but even if I make it public I cant reach it
You can
not true . . .
public Mouse virtualMouse; in script "GamepadCursor" - I try to reach it in another script with GamepadCursor.virtualMouse or ?GamepadCursor.Mouse.virtualMouse
you need to reference the GamepadCursor script on the GameObject before you can access it . . .
Ah, is there no way to avoid having to reference it on the game object? So I do not have to change anything in the editor?
in order to access any script on a GameObject, you have to reference it. that's kinda how everything works . . .
So public Gamepad gamepad would do?
The onyl way to avoid having to reference the object is if you make the variable a static member
Which, if this is a single player game, then having global access to the input would be a good usecase, or making the GamepadCursor a static class.
static is a noob trap
it is a single player game but the player will control two cursors
with the gamepads two joystics
its a little confusing at first that just because they have multiple ways to use it
Does anybody know if it is possible to have a gameobject with a script that can detect collisions of that gameobject's child gameobject's collider?
I have already coded the gameobject to create the childgameobject and reference the collider of the childgameobject, but I do not see a way to use Oncollisionenter method with the child gameobject's collider.
I dont want to create a script for the child if I dont have to
if parent has rb the child collider should already trigger onCollision 🤔
I need the parent gameobject to have one boxcollider and the childgameobject to have a larger boxcollider that is set to istrigger
When my character enters the childgameobject collider, it triggers a change to the parent gameobject
a trigger does not react to OnCollision messages . . .
yeah I know there is the ontriggerenter method, but Im just not finding a way to make reference the child's boxcollider trigger in the parent gameobject script
am I making any sense?
you want to know if the trigger message came from child ? not gonna happen without script on child nvm TIL
gotcha, thanks for the info
The rigidbody parent that gets the trigger event, will have the child trigger collider as a parameter. It collects events for itself and all children on itself. If you want to check if it got the child, you will have to reference the child and compare.
Ahh ^ this . Did not know that
could you explain this further? I checked the documentation but do not see any examples. Chatgpt and google arent working for me either
I usually use overlaps now 
I have the reference to the child game object's collider. Just need to use it within a trigger method
Rigidbodies are the collectors of physics events basically.
rigidbody (OnCollision, OnTrigger, etc happen here for anything under it)
- collider
- collider
- trigger
So just like check if it is the child
void OnTriggerEnter(Collider col) {
if (col == _childCollider) DoAThing();
}
why not just use a Prefab that has components you already need like collider and script that just Invokes an event you can sub to when spawned?
That too
the trigger and collision messages have a parameter. the collider (of the collided GameObject is passed as the parameter for the method. you just need to do a comparison . . .
Im trying to instanstiate 100 or so gameobjects on game start. Im just trying to figure out how to add colliders per gameobject generated. Then need those colliders to trigger changes within the gameobject
I understand the usecase doesn't really answer (more of a rethorical) question
im not sure if im trying to do something too advanced for my current knowledge
Is there a reason you cannot spawn an instance of a prefab
prefabs are not advanced. They are a pretty important concept / feature of unity
that already has the collider on it?
omg, prefabs are a thing . . .
I can make my game object a prefab and instantiate/copy the prefab. That is fine. I just dont know how to have a gameobject with multiple colliders and then reference any which collider all in one script
I have the parent gameobject that has a child gameobject. I want to reference the childgameobjects collider
Im trying to understand what you guys mean in that the parent gameobject should have access to child gameobject colliders
I just dont know how to have a gameobject with multiple colliders
Thats the neat part, you don't
You shouldn't have multiple colliders on the same object unless you want them to act as one big aggregate collider that are all treated the same
also you can have it just spawn as a component w prefab with the things you want already referenced
Gotcha, yeah im either trying to do something impossible and/or the wrong way. I appreciate yalls guidance. I will look more into this
haven't actually explained the use case for this btw
If the alternate colliders are on different objects, you can tell them apart by getting different properties of the object, like tags or scripts and whatnot
Nomnom gave you an example already . . .
right, I just dont understand it yet. Im gonna use what you guys said and try to find more info on it
btw if you ever look into events
SomeComponent spawnedComponent = Instantiate(prefabOfSomeComponent , etc.);
spawnedComponent.OnChildEvent += DoSomethingAfterChildDidSomething;```
or if you want specific colliders referenced in prefab for some reason.
```cs
spawnedComponent.ColliderReferencedA.isTrigger = true;
spawnedComponent.ColliderReferencedB.isTrigger = false;``` @lilac moth
What is considered good practice when your character dies and the whole level needs to be reset to it's starting layout?
depends on the game really. Some times its easier / needed to reset whole scene sometimes you need to just call an event, or something that actually lets everything else handle resetting themselves
79% of good practices are specific to the project at hand and the answer usually boils to
(aside from general good practices like not writing horrific code etc.)
Well i'm completely lost. I'm making a top down shooter similar to hotline miami. I guess i need to launch something once the player is considered dead, any recommendations on how to handle this?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
just load the scene again
I would use an event but I'm biased
since its specific to player and it can even be static
public static event Action OnPlayerDeath
PlayerHandler.OnPlayerDeath += DoSomethingAfterDeathOfPlayer
understood, thank you for the recommendation. I'll look into all of the above mentioned options. When testing stuff reseting the scene definitely works so i might go with Steves approach
yeah game like hotline miami resets whole scene? (maybe), doesnt hurt to learn about events though
you can use it for other cases
thank you for the recommendations, i will do some research then
Reset scene is good too, just need some DDOLs if you want to not reset specific things (like score trackers etc)
i think a reset will do cause literally everything needs to reset.
it's a school project so im not going to make something overly complicated
How are anime wallpapers like this one https://www.youtube.com/watch?v=6bB3BUTy4qw made?
I couldn't find any tutorials online on the process. I tried asking in both the Live2D and Wallpaper Engine Discords and was sent here basically.
(Wallpaper Engine can use .exe's exported from Unity)
How do you make a Live2D model track your cursor inside Unity?
Thank you so much!
hehe this gives me a nice idea for a video project. They're either using the built in function for hardware cursor tracking from OS then into unity , or from it directly in unity using Input.mousePosition
the rotation of char looking at it, is the easiest part.
its main illusion was by removing the application background and keeping it ontop creates the interactive feel to it
So I'm working on a platform fighter party game similar to that of knight club and duck game, and I was wondering how the best way to go about doing player collision with the ground and walls and such. is using raycasts for platforming collision a good idea?
whats wrong with using colliders? (never played those games)
thank you so much
how do you remove the application background?
There is a thread pinned somewhere I can find it when I get back, its something to do with the user32.dll
mind you this is for windows specific
the main thing i want to avoid is using the built in physics because I want to do custom physics, and using the built in physics causes the thing where when the player hits the ground it clips into the ground for like 1 frame then snaps to the ground
you want to do custom physics ?
Sounds like something was wrong in moving the rigidbody component, you tried asking help for original issue ?
my game will have some amount of momentum mechanics which would require a tight understanding on everything that is causing the player to move, hence my inclination towards custom physics. on the point of something being wrong in the rigidbody component, as far as I am aware the clipping into a solid is a very normal thing that results from discrete movement steps and the fact that the "collision" will only trigger once the players collider is overlapping the ground which then retroactively snaps the player to the ground, hence the clipping
I forgot to hit reply in my above comment
Oh ok, You tried the continuous detection modes too ?
I never noticed my character dipping into the ground , I don't work too much in 2d though
so I tried continuous before and it didnt help but now it does, so the issue of the ground seems to be solved, however there are still things like wanting the character to not slide down slopes and other things that come with the black box built in physics (also the physics being non-deterministic which would mean adding online would be nightmarish)
but thank you for helping with the continuous thing
hey is there a way to rotate an object without it affecting the local rotation?
like just the mesh itself or sth
deterministic networking games are pretty uncommon , you don't need deterministic physics to do multiplayer
the mesh should usually be a child, allowing you to just rotate that
ok ty was just about to try that but having someone tell me its a good method makes me more secure
rollback netcode requires determinism, and given the fact that in the fighting game scene it is effectively a necessity, I am inclined to at least use practices that don't shoot myself in the foot if I want to add it later
Yeah I can see that, if you can make your own solid physics sure
hmm there has to be some open source project somewhere to look at maybe or use
helo is it really neccecary to unsubscribe an event on a game object that m gonna destroy anyhow?
If you don't, then whenever that event is called, it will still try to call that function on the destroyed object and fail, which at worst can throw exceptions but at best is still wasted cycles on nothing
sorry i dont know much about how event works backend but how does it calls if the gameobject dosent exists
Why wouldn't it call it? You never removed the callback
It doesn't "just know" the thing that it's trying to call is gone
that's why you have to unsubscribe
Haha no
i see why now thank you
up to you. what I was thinking is you are setting the movingPoint positions at the wrong time in your code, also your Draw method would be better as a coroutine, but I'll let you figure it out
The way you could think of it is: Have you ever had someone get a new phone number and forget to tell you? If you try to call them, you would call the number you have, even though it's disconnected. Unless they tell you that number isn't active, you won't know not to call it
oh my bad my bad i get it 100% now ..the sender will still send the package even though i no longer need it if i am subscribed to it if i am correct ..so i have to unsubscribe to it to let it know i no longer need it
Anyone here smart enough to quickly fix this? It's supposed to not have the same colors touch.
{
for (int y = 0; y < _height; y++)
{
for (int x = 0; x < _width; x++)
{
if ((x + y) % 2 == 0)
{
SpawnHex(_hex1, x, y);
}
else if ((x + y) % 3 == 0)
{
SpawnHex(_hex2, x, y);
}
else
{
SpawnHex(_hex3 , x, y);
}
}
}
}```
i think you gotta skip 1 when you go down on Y, not sure if thats the best way though
Quick stylistic question: Should I keep the var here or replace it with something? Is it acceptable, is what I mean. (idleParticles is a ParticleSystem)
protected override void Awake() {
base.Awake();
spriteRenderer = GetComponent<SpriteRenderer>();
itemSprite = spriteRenderer.sprite;
if (!instantLoad) {
spriteRenderer.sprite = null;
itemActive = false;
}
var mainModule = idleParticles.main;
mainModule.startColor = effectsColor;
}
doesnt matter, but it seems obvious that it would be a ParticleSystem so var could stay as it is
Thanks
Anyone here smart enough to quickly fix
So my Mesh is childed to my drone with the controller and idk why but the mesh doesnt rotate on the Y axis this is the code thats supposed to rotate it: ``` void Rotate()
{
transform.Rotate(0, playerControls.flying.Yaw.ReadValue<float>(), 0);
Mesh.transform.Rotate(0, playerControls.flying.Yaw.ReadValue<float>(), 0);
Mesh.transform.rotation = Quaternion.Euler(new Vector3(playerControls.flying.Pitch.ReadValue<float>() * RotationSpeed, Mesh.transform.rotation.y, playerControls.flying.Roll.ReadValue<float>() * -RotationSpeed));
}```
my head is rotating now
What is the best way to trigger a function once after an animation has started playing? I think I just have a mental blockade right now cause it seems like such a simple problem but I can only come up with really complex solutions...
animation events
wouldnt that need an entire script for the animator?
the function should be on any script thats on the same transform as the animator
yo wdym
Hm but that's not the case for me. I am working on a level director with basically a sequence of scripts that I put into the director game object one after the other. The different scripts of the director access all kinds of objects to spawn enemies and trigger animations. I basically want to be able to tell if the animation has ended and potentially wait for the end or just skip the wait and then go to the next script.
use delay calls probably once the animation starts..if you dont want to wait for the animation to end or need precise timing
Hello! Can someone tell me why this isnt working?
i dont think so
Bro how do I write the codes in boxes
!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.
lol
MATE
did you actually read the bot msg
You got this
I finally got my gamepad virtual cursor to drag objects. However it drags all objects that have the script as soon as I click.
OnMouseDown() anf OnMouseDrag() works on the clicked collider only so I need to simulate this. Hint plz? Do I need to use raycasts?
😂
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
private Vector3 offset;
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
Vector3 newPosition = new Vector3(transform.position.x,transform.position.y,offset.z + target.position.z);
transform.position = newPosition;
}
}`
LETS GO
you gotta use 3 of the back ticks its shift + the key next to "?" before and after your code
depends on the keyboard layout
This "'"?
no thats single quote
Oh god you cant see it
right, now define 'not working', we are not mind readers
this one
You can copy the formatter from the one shown in the bot message
and that location is specific to whatever layout you are using. for US QWERTY layout the ` key is to the left of the 1 key
On English keyboards it'll be above Tab, if I remember correctly. So it's not always in the same place
in the US is above tilde key (between esc and 1)
OHHHHHHHHHH
And you think everyone has that keyboard layout?
damn
it's still three of them
Oh
Nope still not, you need 3 backticks
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
private Vector3 offset;
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
Vector3 newPosition = new Vector3(transform.position.x,transform.position.y,offset.z + target.position.z);
transform.position = newPosition;
}
}```
idc i think the key itself looks the same in every layout
Thereee
wrong
not the case
except only one of those characters is on the ` key in the us qwerty layout. the other character on that key is ~
Now explain the issue you're getting, "it doesn't work" isn't precise enough
bro wait a damn minute
ok my bad i take back everything i said about the " ` " topic
While I was finding a way to paste the damn code I think I fixed the problem
hold on
yeah.. im sorry guys 😭
I think you're not concentrated well enough on pasting the code
figuring it out by yourself is the best way to learn your mistake in my opinion
rubber duck effect
what in the world is the rubber duck effect
still waiting for my amazon package my mom doesnt want to listen to me anymore
just a joke. But do lookup rubber duck debugging
no way theres a wikipedia article about this
very true
its a real phenomenon
almost every coding server
that wikipedia page is probably older than you are
looked it up no its not
How do I get the x and z rotation of what was hit by my raycast?
var angle = collider.transform.rotation.eulerAngles;
angle.z //z
angle.x // x
you can get the euler angles from its transform. just note it's not typically recommended to use those for logic
is there a way get the angle of the polygon that is hit instead of the entire object?
do you perhaps want the normal?
Yeah
the raycasthit provides the normal
How do I get the rotation of the normal though?
what are you actually trying to do with this
can someone tell me what can cause my childed object rotate exactly like the parent rotation*-1 on the y axis and ignores every rotation on the y axis i give it in the code?
I have an object that shoots a raycast from the bottom of it and Im trying to set it's x and z rotation to the rotation of the normal
just assign its transform.up to the normal
child always inherits parent rotation
fixed it exactly 2 sec ago by using localRotation instead of rotation but ty
UIManager & Player both inherit from MonoBehavior
the UIManager has a reference to the player
and the player communicates to UIManager through events
so this way Player has no dependencies
and u can simply drag the Player prefab to other scenes\projects and it should work fine.
I understand this and it's cool
but what about the UIManager? it has a reference to the player, and it won't work if you move it to another project for example. 🙃
also regarding the Player, what if it has references to other classes that encapsulate logic
meaning non MonoBehavior classes that hold some data\logic unrelated to unity
this way if i move the player into another project
ill need all of those classes too
so am i missing the concept of clean architecture in unity?
since tutorials i watch all raise this issue of decoupling components from each other so u can simply drag components into other projects and them working fine
also i come from a full stack web development background
and there's nothing like this
in order for a components\services to work you need the injected services that you use in those components\services for it to function
Honestly any attempt at decoupling stuff like this is just gonna be secretly coupled in a more complicated way. If you use some other way of hooking up these references like DI or just another script, that's still gonna be quite specific to your project. I dont think it's worth it to worry about making a UIManager that can be drag/dropped to any project. Even premade UI assets require you to set up stuff with your own scripts
Especially with the player, and how different itll be between games, I dont really think this will end well
I have a question. So I'm using this code to make my simple enemy ai walk around at random points within a circle;
{
Vector3 randomPoint = center + Random.insideUnitSphere * range;
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPoint, out hit, distance, NavMesh.AllAreas))
{
result = hit.position;
return true;
}
result = Vector3.zero;
return false;
}
void Patrol()
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
Vector3 point;
if (RandomPoint(transform.position, moveRange, out point))
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(point), turnSpeed * Time.deltaTime);
Debug.DrawRay(point, Vector3.up, Color.blue, 1.0f);
agent.SetDestination(point);
}
}
}```
But I don't want it to move at random points within a circle, cause oftentimes it'll just keep going back and forth. Does anyone have any tips for how I could make the movement feel much more natural, like having the random point be within it's cone of vison rather than a circle around it?
Well then what's the way to go?
i do follow coding principles in my code
but when it comes to structuring the project itself
i struggle to know what's the "clean" way to follow 😄
if you want to get a point within it's cone of vision, you'll need to decide on the angle you want it to be in. then when you get the random point, use Vector3.Dot to determine if it is within the desired cone, if not get a new point
In this case I dont think theres a clean way that isnt extremely overcomplicated or detrimental to the progress of your current project. Stuff like player movement would make sense to completely decouple, and these components/projects already exist like the character controller, rigidbody, or KCC asset. Your player and UI will be too specific to your game, that it's already coupled to your game
Hey yo! When my player gets hit by an object. I have it respawn at the start. The issue is that I cannot control the new spawn. I have commented out the things I have been trying to get this working. I am sure it has to do with enabling controls on the new spawn. I just cannot seem to find the magic words that would make it work. Any help would be greatly appreciated.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have this script to create a cone of vision where the enemy can see the player;
{
Collider[] rangeChecks = Physics.OverlapSphere(transform.position, viewRadius, targetMask);
if (rangeChecks.Length != 0)
{
target = rangeChecks[0].transform;
Vector3 targetDirection = (target.position - transform.position).normalized;
if (Vector3.Angle(transform.forward, targetDirection) < viewAngle / 2)
{
float targetDistance = Vector3.Distance(transform.position, target.position);
if ((Physics.Raycast(transform.position, targetDirection, targetDistance, wallMask)) == false)
{
canSee = true;
StartRotate();
}
else
{
canSee = false;
}
}
else
{
canSee = false;
}
}
else if (canSee == true)
{
canSee = false;
}
}```
So how would I add a random point within this fov
ah so you're just going to ignore the advice that was provided and do your own thing then. that's fine too i guess
? I'm not ignoring you? I was just showing you that I already have a script that gives the npc a cone of vision. I was just asking how I would use Vector3.Dot to limit the random point to only be within that cone
have you looked at what Vector3.Dot does?
yes I have used it before
so then surely you know that none of that code you just posted is necessary for just getting a point within a cone in front of the object. and you just need to use Vector3.Dot to determine if the random point you selected is within that cone
its better to disable the renderer than relocate it when its dead
So don't destroy and create. Disable the renderer, move, and then reenable is better? Just making sure I am understanding what you are saying.
yes depending on your player design
Ok, I will try that. Thanks a bunch.
but I want this vision cone to be where the random point will go
yes, reuse objects when possible. you'll put less burden on the garbage collector that way. it's also cheaper to just move an object rather than instantiate a whole new one
congrats? i already told you how to do that. and it does not require any of that specific code to do it. just simply using Vector3.Dot to check if it is within the desired cone and generating a new point until it is

