#π»βcode-beginner
1 messages Β· Page 439 of 1
Awesome that got rid of that error. thanks! Now i have this last error com.unity.modules.accessibility: Package [com.unity.modules.accessibility@1.0.0] cannot be found
I cannot find this in the package manager in the unity registry though. Does it maybe have a different name?
going to just try removing it
was hte transform reset position on the prefad of weapon?
Ok seems like i can remove that accessibility thing since nothing was actually using it
Think you could walk me through how to properly do this? 'GameObject' does not contain a definition for 'StartCoroutine'
StartCoroutine is a MonoBehaviour method, not GameObject.
No but maybe I could make a class just for it and have it only include the delay?
actually idk about that
im pretty sure its the instance
...
void PickUp()
{
print("test");
Debug.DrawRay(cam.transform.position, cam.transform.forward*200, Color.red);
heldWeapon = hit.transform.gameObject;
heldWeapon.transform.parent = weaponHolder.transform;
heldWeapon.transform.gameObject.layer = LayerMask.NameToLayer("Weapon");
heldWeapon.GetComponent<Rigidbody>().useGravity = false;
heldWeapon.GetComponent<Rigidbody>().isKinematic = true;
heldWeapon.transform.localPosition = Vector3.zero;
heldWeapon.transform.localEulerAngles = new Vector3(0, 0, 0);
heldWeapon.GetComponent<Collider>().enabled = false;
}
}
well the prefab is attached to an empty
and im changing the transform of the empty
the empty is heldWeapon
its called "pistol" in the editor
I meant their inspectors - where all the components are displayed...
But in any case, the Pistol game object's local position and rotation are changing, and they just won't do that on their own - they'll stay consistent relative to their parent unless something else is affecting them.
Maybe see if something unexpected is referencing the Pistol - enter play mode and drop and pick up the pistol and dance around a bit. Then try right clicking the Pistol game object in the scene hierarchy and selecting "Find References In Scene" to see everything which references it. Failing that, right click on it's Transform component in the inspector and do the same
when I did "Find references in scene"
the weaponHolder components Pos isnt changing
but the actual pistol is
It will filter the scene hierarchy to show objects which reference it. So go through whatever's present in the filtered hierarchy, and make sure that the scripts which reference the Pistol are really meant to
this is the heirchy when picked up
Pistol is the thing thats changing position
this is when i did "find references in scene" isnt Player meant to be here?
Does anyone have any idea how to get a collider to jump along with the character animation?
im following a tutorial and I want to add on a little bit by deleting some of the game objects. I have the object in as a prefab it seems as I imported it as an .fbx from blender but when I try to use the "Destroy(Easy);" the Easy party gets underlined red and says it doesnt exist in that context
Yeah that seems very strange... Are you in play mode?
Guessing you finally solved your strange .net SDK issue
yes FINALLY
How did you solve it?
i went to a c# discord and someone sent me over a script that i looked over and ran
yup
this is very very wierd
idkw ahts moving it
i think it maybe fixed my path in environment system variables to the correct thing? not exactly sure what the issue was still but its fixed now thats all that matters
Does Easy object exist in your scene? and do you have a reference to it in your script? show your code helps alot here
Try "Find References In Scene" directly on it's Transform component in the inspector, for funsies
Easy object does exist in my scene, what do you mean by reference it in my script?
im doing it on the transform
im doping it on "Pistol"
which is an empty
theres the code
hover your mouse over Destroy, does it take a gameObject as a paramater? if so don't add the .Easy part to it
When I remove .Easy from it there is no red line. but how would i identify the specifi game object i want destroyed
THere are a variety of ways to "Find" a gameObject in the scene, also realize Destroy(this) will destroy the very object running the current script, so that may not be what you had in mind
- Look up methods to find objects in the scene.
- Or reference that object in your script via the inspector instead.
Either way, go through the beginner pathways on unity !learn before continuing with your project.
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
I think it'd make sense that Player doesn't show up when performing FRIS on the transform, since the PlayerMovement script only holds a reference the game object and not the transform. But Player should show up if you FRIS the Pistol game object... scratch that - they perform the same search. It's super weird that Player doesn't show up at all π€
Does your console just log "test" once when you pick up the gun, or is it spamming it?
yeah thats definitely not what I wanted to do
Which object do you want to destroy
i only have 3 objects in my scene Easy, Medium, and Hard which are literally just text that say that word
and I want to destroy easy
Okay, so which one do you want to destroy
Then you should make a variable that holds a GameObject and drag it in
Do you know how to make a variable
wait i think i get what youre sayin
yeah i was just confused what you meant by drag it in ill try again right now
what variable type should it be?
consider making a new empty object that holds your script and acts like a manager of objects, then reference the object you want destroyed in there and do it from that object/script
@cedar bone in your earlier code/video, your raycast for the pickup is looking for objects on the "Item" layer, but Pistol is on the Weapon layer...
Did you change that in the code after recording the video? π
Yeah that worked thank you so much for your time
Thank you for the help!
once
nah it changes the layer
nah it makes sense cause it should only be moving it once, when i run PickUp()
but weird thing is its not lighting up when I do that
so its probably too fast for me to see
Yeah... I just wanted to definitively make sure, because that was the only code which you've shared that deliberately alters it's position/rotation...
It's super confounding. The only thing I can think of is that some script is referencing it by accident... but then, nothing shows up in the FRIS search...
I guess I might try deleting the object while in play mode and adding a cube as a child of WeaponPos, ensuring that behaves properly. Then manually assigning it to heldWeapon and seeing if it's behavior changes... at least that might narrow down the potential sources of the problem...
Does WeaponPos have any scripts on it?
my character automatically moves when i press play without any inputs
thank you for this information, I will charish it forever
hasStarEffect here should turn true if it passes placedPosition == grenadeStarLocation, right?
its always giving me false. I am not sure why
how you verify it
Am I doing something wrong here? My unity script doesn't have public void Start() referenced when the DLL does but I don't imagine that would stop it from working entirely right?
not sure what you're attempting to do here, but hte default Start() method is private
public void Update works fine
why do variables like if i have a float walkSpeed = 5f; and i want to change it to 10 so i put it as = 10f; it doesnt change it and stays at 5?
I see no reason why start being public would break
How are you modifying the variable?
And where
its above the start void and itsa public
in the inspector do a reset on the script to get the changed values
where do you change the value to 10? in your code? from the inspector? need more information . . .
in the code in visual studio
assigning a value to a variable at the top of the script (class) will set its default value. once that value is change from the inspector, it will always use the inspector value . . .
What I'm trying to do is find the one audio source, get its gameobject and slap a component that links the sound to a slider onto it
so what's the problem, exactly?
It don work
I'm gonna try it in update where I instantly flip the bool to false
the Start method?
Either that or the entire block inside of it, yeah
place a log inside to check that it runs . . .
I'm worrying that it's cause the Unity script linked to the dll via an asmdef doesn't have Start in it
did the log display from Start?
It says it added it once
Which is exactly what I wanted to happen
Buuuut, it doesn't work in the slightest
The mixer linker automatically defaults to being linked to the master slider which mutes everything so I know it's not adding the component
FindObjectOfType will return the first active AudioSource it finds in the scene. the returned component will not always be the same . . .
There's only one audio source in the scene
Pretty sure it can't be different, right?
I'm a bit confused as I thought I already declared what I needed to?
Relevant code lines.
Say, if the audio source is above my component that does the searching, that wouldn't be a problem would it?
The audio source is on Wave
if it's not adding the component, then mixer.audioMixer should produce an error cause mixer would be null . . .
if its not static you cant use the class directly, you'd need an instance
Then it should be working fine
But it's not
can't you just look at the GameObject and check if the component is added?
No, actually
Else I would just add the component manually and be done with it
It's not even uh.. Visable in editor
All the meshes and scene are gone because I desperately need storage space
how is the GameObject not visible in the editor?
no idea what that means . . .
Cause I need to build the file via a bundle builder and if I just update it in unity, none of the meshes are gonna be there
I need to add it after the scene loads so that it links up without doing it in the editor, which is messy but I don't have the storage space for 10GB worth of rocks and castle pieces
Surely they're gonna be there early runtime
They should always be there, looks like it is adding the component though
Maybe the last line is just messed up
Nope that's.. The only field the component has
Got it. Thank you!
i got a script that has public GameObject gun; but its not letting me attach my game object gun to it, the gun has no script or anything its just a cylinder
Y'know.. I could just make my own slider to mute it
That'd probably be less jank than adding stuff at runtimee I don't know that works
is that too vague
are you trying to assign a scene GameObject to a prefab (asset in the project folder)?
no its not in a folder its just in the hierarchy its not accepting any sort of game objects i just made a new random sphere and it wont accept it
im attemtping to make my enemy ai pathing with NavMeshPlus for 2D
or wait if u meant the prefab in a folder i do have that in a prefab folder
im recieving the error Failed to create agent because it is not close enough to the NavMesh
well i feel like a goober i just took it out of the folder and it worked lol
interesting i put it back in the folder and it loses the game object nvm
you can't assign a scene GameObject to a prefab because the prefab does not exist in a scene. it doesn't know which scene the GameObject is from. when the prefab is instantiated into the scene, you must search or pass a reference to the scene GameObject . . .
then its not close enough to navmesh π€·ββοΈ
Can I use a foreach loop as well as findobjects of type?
Just
{
if (audio.name == "Wave")
{
mixer = audio;
}
}``` looks like it'd work
that will be horribly slow and resource-intensive . . .
Atp I do not care, I just want to get this audio source π
Plus it'll only run once in start
also, FindObjectOfType returns a single component. it's not a collection of objects . . .
That's fixed with a single s
then yeah, that will work . . .
did you even check the GameObject name after calling FindObjectOfType. is it the correct one?
No
I did debug it and it was the complete wrong thing
Sick, the slider works
I can probably add that other component now
All fixed, I should use foreach loops more
foreach didn't do anything. you use a loop if you have more than one type of object. you stated there was only one: this was the issue. now you check one each to find the correct AudioSource . . .
There is only one in the scene, I forgot the player is added to that scene, which contains like 50 to look through
I found the problem
its the rigidbody
but i set it to kinematic tho
so idk y
then there isn't only one . . .
have you no shame?
do u have any recommendation for doing this im struggling on finding a way
its 2D and as close as it really can get
what exactly does it mean when it says not close enough, what is it checking for
Give it a reference from somewhere where you do have it. At runtime.
does anyone know the "enabled" equivalent for component?
There isn't one, because a component has no concept of being enabled
That is something Behaviour adds on top
You could add or remove component. Not the same thing, but it depends on what you want to do
Some non-behaviour components have an enabled state, but it's not something standard so you have to handle those ones explicitly
Damn because I want to momentarily pause my character's rigidbody and I thought i could use the same logic as making a sprite renderer pause momentarily
guys i was following the unity tutorial course but their code had autocomplete but when i type my code isnt showing suggestions how can i enable them i tried reinstalling both unity and visual code and also tried to install some extra extensions/plugins...
how do i enable it i cant find anything on google
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
The closest thing for Rigidbody would be detectCollisions and Sleep/WakeUp
You can of course also just disable the game object
is there a way to freeze the location of my character momentarily then?
constraints lets you do that
Set the velocity to 0
rb.constraints = RigidbodyConstraints.FreezePosition;
No no, i just want my character to not despawn but rather freeze for a short time in the air
Oh alright then ill give it a try thanks guys
Okay got a problem
Is there a way to translate this for rigidbody2d?
rb.constraints = RigidbodyConstraints2D.FreezePosition;
Lol i put Rigidbody2DConstraints
Hey is it normal to be stuck on "completing domain"?
If you're actually stuck on it, that would be a bug
Nope
Guys, how to animate padding property in layout group components in Animator? Animator don't see this properties
i need help asap, i have a problem with my code. my GroundCheck Trigger isnt working, thus making jumping impossible. I do not know what to do at this point
π
How would I unfreeze the character?
Set it to RigidbodyConstraints2D.None
rb.constraints &= ~RigidbodyConstraints2D.FreezePosition;
That works too, but since it's the beginner channel I wasn't sure if I should start throwing bitwise operations in
!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.
If you're going to do that, you will probably also prefer rb.constraints |= RigidbodyConstraints2D.FreezePosition;
Which will merely add the position constraint on top, rather than make it the only constraint (so if you had rotation constrained previously, it will remain constrained)
i want a float in a script to have a 50% chance of becoming negative, how do i do that?
Because you have code which makes this happen. Look at the #854851968446365696 more on how to ask
Which part do you struggle with? You can get a random value from 0 to 1 and then compare it to 0.5 (which is your chance). If the random number is greater or equal to your chance, then do your logic
nvm i have another problem.
i have a weapon script that calculates weapon spread, however when i use a shotgun, sometimes the spread is entirely vertical, sometimes entirely horizontal, sometimes a small circle, sometimes a large circle, and these results are always the exact same BASED ON THE DIRECTION IM LOOKING AT.
so, one direction will always give me result x, another direction will always give me result y and so and so.
From a quick look, you're just applying a random x and y both generated independently. Theres no care about it being a circle so x or y could individually or both be 0. Also you should probably normalize the random offset then rescale the vector so it's the length you want
I love your art style btw
@eternal needle
what makes it happen
im not really sure what the issue is. you didnt say what was wrong
it could be due to your setup with the rigidbody or collider. sorry i dont do 2d so not exactly sure of the settings there. from google i see one fix could be setting the rb mode to continuous
i decreased the jum force and it fixes it
it still happens if you jump frfom a heigh place
@eternal needle it happens too when i walk into walls
Did you try the suggestion above? Im really not sure much about 2d but im sure others would be able to help if you show the settings you have on the rigidbody or other components of the player
somehow it fixed it but only after i made the collider a capsule
Most of that isnt needed. You simply set it to kinematic and that's all. If its moving still, thats because you're either moving it via the transform or you have it parented under a moving object
Also dear lord cache that GetComponent
no it isnt the last two, becuase when I delete the rigidbody it stops moving
this is how it moves btw
its weird, when I delete the rigidbody it stops doing that
I cant see that on mobile !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.
Also I'd assume you're moving it via MovePosition then
im not
i have no other references to that Game Object
im talking about the video
this is the only reference to that GameObject
I have absolutely no idea what you're showing with the video
the pistol should stya in one position
but because of the rigidbody it isnt
its moving around the whole thing
and it gets fixed when I remove rb
Honestly it's a pain to even try looking around in the video on mobile. But I can see it looks like the object is parented under your player, in which case it will move with the player
Kinematic rbs do not move on their own
I also sent some msges later that go more into depth
for example tehres no scripts referencing it
just type from: TomSipsOnCurry into the search bar
im gonna go to sleep, can u pls @ me if you find an answer
π€·ββοΈ the pistol is very clearly parented under a few objects so im not really sure what else you're looking for.
Kinematic rbs simply wont move around by themselves, they are ignored by the physics system
its not moving with them, that's the problem... and its local position is changing... it is a bit weird
Well from what I see its parented under something called the CameraPos
Which sounds wrong
For stuff like this, I'd recommend just recreating the object with as minimal setup as possible then adding parts back until it recreates the same issue
Hello guys, I'm back, please tell me how I can do the following:
I have my own method by which I improve a certain upgrade. but I have several upgrades. I also have several variables (double): CashUpgradePrice, CashUpgradeProgress, LevelExUpgradePrice, LevelExUpgradeProgess. So, I need to pass some value through the method and this value determines which upgrade I need to improve. Please tell me I don't know how to do this
I already have a value passed through the method:
{
}```
Use an If statement that checks what UpgradeName is and handle the results
I had such an idea in my head, but I think it won't reduce the size of the code for me π
Then your current attempt at passing the upgrade name isn't going to be useful
How are you storing the data for these upgrades, currently?
A simple option is to replace the individual variables with an array of doubles and the string with an enum. then its just a case of
array[(int)UpgradeName] = //something
PlayerPrefs.SetFloat("Cash", Cash);
PlayerPrefs.SetFloat("Diamonds", Diamonds);
PlayerPrefs.SetString("Difficult", Difficult);```
Oh boy ...
Well, in that case, just save everything as floats, and just do PlayerPrefs.SetFloat (UpgradeName, UpgradeValue); and be done with it
I know that I don't know how to code lol, as I was taught
Maybe anyone know how do I can learn coding on C# more good?
nvm i just fixed it by rotation the bullet and applying force to the bullet's transform.forward rather than setting a new vector3
what does this mean?
what about 'could not be saved' do you not understand
hello guys, i wanna be a game developer and i am starting my journey. which coding language should i learn? and have any good tutorials?
Unity uses C# and !learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh thank you, do you know any good tutorials and etc for c#?
C#*
oh Thank you π
Did you figure it out? I never used the 2D version. Usually in 3D if the agent isn't close enough to the mesh or it wasn't bake so it can't snap onto it..idk maybe in 2D check the z position
!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)
!vscode
I have a question about Physics material 2D :
I saw I could add a physic material both to the rigidbody and the the collider of an object. Can I just put it on any of these or is there a difference/good practice for that ?
It's up to you.
Putting it on the RB applies it to all that body's colliders.
Applying to a single collider applies it to only that collider
It's pretty straightforward
Aaaah ok I see! So RB for the whole object, single collider just for a part of it
thanks π
I have an other question :
I'm making a simple ball breaker game, so with a paddle and a ball. Is it normal if the paddle doesn't have the same speed when I have its inspector open than when I don't ?
I apply a vector2 right/left every frame when the player press right/left, multiplied by speed and by deltatime, to give some context
That means your code is framerate dependent
I apply a vector2 right/left every frame when the player press right/left, multiplied by speed and by deltatime
What does "apply" mean?
Providing your actual code would be more useful
If you're setting a Rigidbody's velocity, then you should not be using deltaTime
Yup, here is the whole controller :
Rigidbody2D rb;
public float moveSpeed;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Start(){}
void Update()
{
TouchMove();
}
void TouchMove()
{
if (Input.GetMouseButton(0))
{
Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (touchPos.x < 0)
{
//move left
rb.velocity = Vector2.left * moveSpeed * Time.deltaTime;
}
else
{
//move right
rb.velocity = Vector2.right * moveSpeed * Time.deltaTime;
}
}
else
{
rb.velocity = Vector2.zero;
}
}
right exactly as I said
ah that's probably the issue then
See here
hey, no i didn't figure it out when i bake the mesh it says 0 sources and it doesn't come up with the overlay gizmo showing the walkable area, could be from the z axis and its not detecting anything. i think it also has to do with order layers from what i've heard ill check that
I put this in my player controller's Start() and it seems to have had no effect on my mouse position. Cursor.lockState = CursorLockMode.Locked;
Is the code actually running?
yup, just dropped a debug right before it
Also did you give your game window focus?
it seems to lock and hide when I click though
Very common issue where the game window is not actually focused
then it's working fine
This will not occur in the build in the same way. Just an editor thing
Note that the Unity Editor has special handling for this because it's important you be able to still interact with the editor window itself while the cursor is locked
ok I guess I just didn't have focus, yea editor I can understand needing to prevent that
is it normal when it locks it to also hide it?
yes
added Cursor.visible = true; but that didn't turn it back on, guess I'll have to create a little crosshair at center
https://docs.unity3d.com/ScriptReference/Cursor-visible.html
Set this to true to reveal the cursor. Set it to false to hide the cursor. Note that in CursorLockMode.Locked mode, the cursor is invisible regardless of the value of this property.
I am trying to wait/get an event when an AudioSource finishes playing... so I am checking isPlaying but paused clips now trigger as completed π€¦ββοΈ
Is there a simpler way I am missing? π
yep, for what I see people compare the time to 0 or to the full lenght and do some fuzzy stuff to know if something is paused or not π
Checking the time would be my first thought to do tbh
ya, seems easy enough
it's not a thing built in but presumably since your own code is pausing/unpausing it, you can make your own bool for that
yep, I was scared of the audio listener doing wacky stuff but I found this.audioSource.ignoreListenerPause = true; so I can do it π¦Ύ
niice! good researchin π
Guys is there a way to have a parabolic trajectory without physics?
i mean yes, u can do custom math
thers a formula for it.. just convert it to c# and tada
so what translate using the formula?
Need to show the path of a projectile? Not paying attention in Physics catching up to you? No problem! Learn how to draw the trajectory of a projectile would take using a LineRenderer and one of those pesky physics formulas you said you'd never use again! Show a visualization of where those objects will go!
We're using a grenade in this case, b...
thank you!
Verlet intetgration
Y = Y0 + VY0 * time + 1/2 * A * time^2
(keep in mind, I use y0 and vy0 because I use the big boy time and not dt)
Yi+1= Yi + VYi * dt + 1/2 * A * time^2
VYi+1 = VYi + A * time
if you want to use dt
is there a way to make a script that runs when the game is run no matter what scene your in? like the equivelant of a godot autoload?
thx
Put this on your starting scene
I am working with a team of people to create with CAD software specifically for a robotics program (specified parts, not like other CAD softwares) and we want to make it possible to automatically generate chains that connect two gears. I attached an image of what i am trying to do. Ive experimented with unity splines but i couldnt find any way to automate it, it is good for generating a predefined path for chains to generate on though. So what is the best way that i can generate these chains around two selected gears of any predefined size.
My first attempt would be to place empty transforms at each cardinal direction (NSEW) of a gear (as children). I haven't used splines but you should be able to use the position vector of each transform β for both gears β to create a spline around them (remember, the front gear will not use its West transform point and the back gear will not use its East transform point)
You need to figure out how to add the bezier curve to round out the spline along the gear, but that shouldn't be too hard . . .
If you want to pause or unpause an audiosource then use Pause() or Unpause()
2 half circles at each gear and 2 lines from the tangents of each circle/ If you want variable tension in the chain that's a whole different story
does anyone fancy looking at some code and figuring out what on earth ive done
because it dont work right
don't ask if you can ask a question
its a massive block of code i dont know if i should send it all
use pastebin for large chunk of !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.
will do, im gonna send a picture of what my current unity looks like idk if itll be helpful to look at the hierarchy
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What is the actual question though
the question is
there is a slider going left to right and there needs to be green areas which highlight where the player should cut but the green areas are all wrong ever since i realised nothing was coded to fit any screen size other than the one i was working on
so the green areas just need to be randomly placed within the range of the slider
which may be off aswell
AdjustSliderSize() references Screen sizes, but is only called at Start(), never in a Update() call, so changing the screen would not re-call the Adjust
anyone know how i can stop it from adding multiple score? ```js
private void OnTriggerEnter(Collider other)
{
if (other.tag == "ball")
{
if (tagchecker.tag == "ingame")
{
if (teamchecker.tag == "blue")
{
redscorenum = redscorenum + 1;
string redscoretext = redscorenum.ToString();
redscore.text = redscoretext;
}
if (teamchecker.tag == "red")
{
bluescorenum = bluescorenum + 1;
string bluescoretext = bluescorenum.ToString();
bluescore.text = bluescoretext;
}
//StartCoroutine(die());
}
}
}``` when the ball enters the trigger zone it goes thru multiple times
You'll get one OnTriggerEnter per collider pair
Does one of your objects have multiple colliders?
How about you log this and other to see what's colliding with what?
Confused why this is happening:
I have this calc Mathf.Floor(hit2.point.y / chunk.cubeSize)
where chunk.cubeSize is fixed at 1f
and I print out the hit2.point and the resultant calculation immediately after it
1 time it gives 64 for a hit point of 64, then sometimes it gives 63 for a hit point of 64. Same input in both cases, but the calculation deviates
Floating point precision
There's no way the same input is giving different results. hit2.point.y only has to be a tiny bit less than 64 for it to be floored to 63.
Sometimes that division comes up as 64.000001 and sometimes it comes up as 63.9999998
Those floor to different values
Since printing a vector in Unity rounds to two decimal places, both would print the same value for hit2.point
Hrmm, how to solve that? I expected a number divided by 1 to pretty much always equal the same thing
how did you print out the point?
The default is to only show 2 digits
print(" Hit Point: " + hit2.point + " Cube Point: " + cube + " Hit Nornal: " + hit2.normal);
print($" Hit Point: {hit2.point.ToString("F8")} Cube Point: {cube} Hit Nornal: {hit2.normal}");```
If chunk.cubeSize is truly always 1, then the division is not the source of the problem. The hit2.point is slightly different.
Hrmm F8 showed it to be 64.00000000
Hit Point: (0.68492380, 64.00000000, 0.95993330) Cube Point: (0.00, 63.00, 0.00) Hit Nornal: (0.00, 1.00, 0.00)
but when this happened did floor return 63?
yes, in the print I print out cube vector as well, shows 63
for completeness here's the entire cube calc Vector3 cube = new Vector3(Mathf.Floor(hit2.point.x / chunk.cubeSize), Mathf.Floor(hit2.point.y / chunk.cubeSize), Mathf.Floor(hit2.point.z / chunk.cubeSize));
Can we also print chunk.cubeSize and Mathf.Floor(hit2.point.y / chunk.cubeSize)?
Is cube size also a float ?
yes cubeSize is a float, fixed at 1f
well let's go ahead and print it just to make sure
I donβt think that actually guarantees that it is stores in memory as exactly 1.0
https://www.spawncampgames.com/paste/?serve=code_890 could someone give me an extra set of eyes.. i cant figure out why my text keeps getting cutt off.. i kep adding margins and stuff but i think they are in the wrong place
What happens if you just do not do the devision ?
Hit Point: (0.45427690, 64.00000000, 0.55240290) Cube Point: (0.00000000, 63.00000000, 0.00000000) Hit Nornal: (0.00, 1.00, 0.00) cubeSize = 1.00000000
What does the division result print?
Is the text wrapping to the next line?
Solved β
yes, thats what it was
thank you
Sorry I was too slow
no worries
i figgured out by changing the padding around.. and then when it wrapped it centered it once.. and all the edges were cutt off
so thats when i realized it was wrapping... easy enough to disable it
Cool
Hit Point: (0.66471980, 64.00000000, 0.98727500) Cube Point: (0.00000000, 63.00000000, 0.00000000) Hit Nornal: (0.00, 1.00, 0.00) cubeSize = 1.00000000 div = 64.00000000
Divisopn added, now suggest Mathf.Floor is at fault
Cube Point: (0.00000000, 63.00000000, 0.00000000)
Hit Nornal: (0.00, 1.00, 0.00)
cubeSize = 1.00000000
div = 64.00000000```
lies
Or if it's a floating point precision error, add 0.0001f to the equation..
Hi
He's using Mathf.floor. and it's doing what it does
ahh soo non-issue lol
It rounds down
Mathf.Floor(hit2.point.y / chunk.cubeSize) is returning 63 sometiems 65 other times
lol.. it skips 64?
Use roundtoint
opps sorry, 63 sometime and 64 others
I didn't notice what server I was in. My bad. I don't work here.
I want it to floor it though, RoundToInt could Ceil it in cases
But it will ceil it to 64
i need an UI element in unity that works like a radio button, basically i have for example 3 of them and i can select 1 of them
more of a #π²βui-ux question
You can also consider a https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-Dropdown.html
how can I make this more efficient? I basically want to spawn the object randomly within the box collider but in a grid layout, and I also don't want it to spawn on top of itself. ` float minX = Mathf.Ceil(col.bounds.min.x);
float maxX = Mathf.Ceil(col.bounds.max.x);
float minY = Mathf.Ceil(col.bounds.min.y);
float maxY = Mathf.Ceil(col.bounds.max.y);
Vector3 randomPosition = transform.position;
while (randomPosition == transform.position)
{
float randomX = Mathf.Floor(Random.Range(minX, maxX));
float randomY = Mathf.Floor(Random.Range(minY, maxY));
randomPosition = new Vector3(randomX, randomY, transform.position.z);
};
transform.position = randomPosition;`
is there a method in unity to use for creating assets automatically ? i tried OnValidate to make sure assets exist for my given data and if not create the asset/save to asset datbase but apparently you cannot do such ops in OnValidate. so is there some built in function that i can run ? i dont want to have to keep manually remembering to press some ui button to verify / regenerate assets every time i change some data
if it works move on to the next thing. dont worry about optimising until its a problem
What's the use case? What kind of data are we talking about?
meshes based on changes to spline shapes
how do you change the spline shape? A custom editor tool?
or is this using Unity.Splines or something
You can do asset stuff in validate if you delay it by a frame, like with EditorApplication.delayCall
Not that it's the proper way to do this, but that is a thing that exists lol
im changing the tangents and positions of the end points so the curvatures change so the mesh assets need to refresh, i dont want it to regen every time i change them only when i defocus the scriptable object or something to prevent performance issues
hmm that seems hacky lol
Sure but how? Through a custom editor tool?
or just in a ScriptableObject inspector?
currently i use a ui button to call a regenerate method
but some times i forget to press it and so the mesh assets no longer match the spline
SO you edit by typing in numbers etc to the inspector?
Couldn't you do this through a custom editor?
basically at the end of OnInspectorGUI you update/save the assets if there were changes?
oh umm
I've encountered an issue with Prefab Overrides. I've applied a script to one of my gameObjects within a prefab. The script requires the assignment of a seperate gameObject so it can reference it within the objects script. However, after apply the script and its corresponding gameObject, I am unable to apply the override. Could someone explain what my problem is? (Image for reference)
the prefab is not going to be able to reference an object from a scene
yeh you can only reference prefabs in your asset directory not instanced versions of it
Hmm... Is there a well known work-around?
no because once you save and exit that reference is gone
Workaround? no.
If you want a prefab to know about an object in the scene you need to assign that reference in your code
after instantiating the prefab
Alright then. Will do! :D
I created a shader and am trying to set it as a materials shader but it is not showing up as an option. What could be wrong?
i tried this but still i can select the 3 options at the same time
i need to select just 1
Solved it, tysm!!
then you didn't set it up properly
A Toggle Group is not a visible UI control but rather a way to modify the behavior of a set of Toggles. Toggles that belong to the same group are constrained so that only one of them can switched on at a time - pressing one of them to switch it on automatically switches the others off.
i did a gameobject with toggle group component then i put some gameobjects as child with tiggle component
Ok sounds like you didn't read the instructions.
Read the Description part, it says how to set it up
Does Anyone Know how to do Target Rotations The left one should do the same as the right one?
a okz, now i understand, it is working now.
would i be able to do the asset regen in the editor script's OnDisable call ? or is that also not allowed similar to OnValidate in the object's class
What do I put here? Iβm not sure what scopes mean
@shell gorge
Oh I need to but a .com link?
this is not a code question. and itch.io is not a package host
if your actual intention is to upload your game to itch.io then you need to actually build the game, and upload the build files to it.
well wtf are you even trying to do here?
my state doesn t change, and this appears in animation. If i press manual on the bool variable work but automatic don t. I don t un
derstand why.
Trying to post something for android, but someone said I need to put an itch.io link there so I did
^ go on itch and start the process..
Oh. Someone said to do that. Sorry.
whoever said that was entirely incorrect
it'll ask u for a build.. (for webGL it'll include an html file) just zip it up and upload it to itch
Okay, what link do I put?
Oh
you just build a game page..
you don't put anything there. that has literally nothing at all to do with building your game or hosting it on itch
itch's got u
they probably recommended itch so u can get play testers
w/o needing to have an app and them download it
the screenshot you've shown is for adding a package repository to add packages to your project via the package manager
Can someone just message me privately about this please? I canβt keep looking At one and anotherβs comment. Is making my head weirdπ
Here's what you need to know:
This screenshot provided here #π»βcode-beginner message
Has absolutely nothing to do with releasing a build of a game
So everything you know about this screen you can just ignore it
It's utterly unrelated
Iβm confused.
Yes we can tell
I want to make it for android, thatβs all
Yeah Iβm very am.
So I donβt do anything with package manager?
fix it in Edit / Unity -> Preferences -> External Tools
The slash means "Or"
BaseHeathbar.slider.value -= 1;
that will subtract one right
It is the same as BaseHeathbar.slider.value = BaseHeathbar.slider.value - 1
so its just setting it to -1
It's setting it to BaseHeathbar.slider.value - 1
got it thank you im trying to subtract 1 from that value
How do I fix it?
Did you consider reading the warning that tells you exactly how to fix it
This?
That would indeed be the warning you showed. Unless digi snuck into your room and saw something we didnt
You did that one
And it brought you to another one
that tells you what to do
you need to read the error messages
If you can't read it on the window you're looking at why would you be able to read it if I type it out
Idk where it tells me what to do, it just says βexternal toolsβ
You already went to external tools
Did you just forget your own screenshot that you sent when you were there
look at the warnings and read what they say
Under Installs, click the gear for the version of unity you are using, and Add Modules
Did you actually install it through the hub
Install what?
Unity
You're going to have to find the installer you used to install the editor
Or delete the editor and reinstall via the hub
I have unity
I donβt think I have an editor
then what are you editing in
Downloading a editor now
It would be quite difficult to use Unity without Unity
Unity 2021.3.3f1
Yes you do
You have shown pictures of it
Speaking of pictures, for the love of god do not take photos of your screen 
and did you install that through the hub
No I think from Unity, I donβt remember how I got it
I canβt, Iβm sorry.
So then you'll need to run whatever installer you got
Yes you can.
Discord can be accessed via browser
Hell, you could even email the screenshots to your phone if you have to
1 of 2.
Okay.
The editor is now done. What do I do now?
You actually already had an editor. Didn't you want to get the modules? You need to install the modules you want now
Did you install a NEW editor, or the same one again?
Or did you do it via the hub?
Oh.. yes I want the modules so I can finish this
Do I show in explorer and add modules in the folder?
The strange solution I came up with to my Mathf.Floor problem is to do this prior to the Floor call
if(hit2.normal == Vector3.up || hit2.normal == Vector3.right || hit2.normal == Vector3.forward)
hit2.point += hit2.normal * 0.02f;
else
hit2.point += -hit2.normal * 0.02f;
hi helpful people
uk how i can do onTriggerEnter then do something right, can I disable a trigger after it is triggered? I only want the trigger to trigger once
can I disable a trigger after it is triggered
sure, why not
You can do anything you want. That's the beauty of programming
How would I make a t variable (for Quaternion.Slerp) where the t function is different for every function?
kind of like a private variable for a class but for functions
what do you mean by "different for every function"
kind of like a private variable for a class
If you want a private variable in your class, make one?
t is a float parameter btw, not a function in Slerp
private float myValue
Done
if i define it inside a function
The code in methods which return Ah I misreadIEnumerators is also instanced when you call the method - so you could do that sort of encapsulation in a coroutine, if individual class instances don't fit your use-case
and i define it in another function
how can I do that?
What?
can I make it so they have 2 different values
do what? Disable a collider? Someone answered it
Finish your message before hitting enter
yeah mb
if you define a variable inside a function it's a local variable and has nothing to do with any other variables anywhere else with the same name.
so its not accessible in any other function?
local variables are not accessible in other functions no
that wouldn't make any sense
Thank you!
in general variables are only accessible in the scope they are declared
with public (and other nonprivate) members being the exception, and then only through the . accessor
i have a method with a default parameter called defaultDamage. This defaultDamage should be modified in Setup by the attached switch. The numbers printed in Debug are correct but the values are not getting set in the method. What am I doing wrong?
what's printing?
and what do you mean by "the values are not getting set in the method"?
totalDamage should overwrite defaultDamage. I can see in the debug.log that the setup is receiving the correct number but it wont take over for the default value for method "buster"
Also I'm a little confused because it seems like Buster calls Setup and Setup calls Buster?
it wont take over for the default value for method "buster"
I'm not sure I understand what you mean by "taking over the default value"
no that setup is for a different script called bullet. its not calling itself
So I'm a little confused if the left screenshot is calling the function on the right, or vice versa
defaultDamage is 15. If it receives totalDamage, defaultDamage in "buster" method should be set to that
its calling a different setup. they are not related
So this part is not related?
so the one on the right is calling the one on the left
no thats a different setup for a class called bullet. the one on the right is calling the one on the left, correct
the one on the left is not calling, right
And it is - for that invocation of the method, the value within Buster will be whatever totalDamage is. You can verify that for yourself by sprinkling in some Debug.Log()s
Why don't you do Debug.Log("Buster called with defaultDamage: {defaultDamage}"); @copper orbit
on the first line of Buster
I'm worried you're expecting that calling the function like this:
Buster(defaultDamage: totalDamage) means that all future invocations of Buster() without a parameter will have that new default value
Is that what you're expecting? Because that's not how that works at all
that is what i am expecting
yeah you're misunderstanding the default value
how can i fix for it to be permanent once received?
A method parameter does not have any persistent state - when the method executes, it's just whatever value is passed in as an argument at that time.
In your code you've specified a default value for the defaultDamage parameter as 15. The only time that that default value matters is if you call method without specifying an argument for that parameter, e.g. Buster() instead of Buster(someValue).
The only way to change the value of a parameter is to pass in a different argument when calling the method.
save it in a member variable
The only thing having the default parameter value (i.e. doing void Buster(int totalDamage = 15) does is that calling Buster() is equivalent to Buster(15)
Buster(defaultDamage: totalDamage) is just using named parameters - it's also equivalent to Buster(totalDamage)
also the name defaultDamage for your parameter is confusing - it should probably just be called damage to avoid confusion
you could do this:
public void Buster() {
Buster(this.totalDamage);
}
private void Buster(int damage) {
// normal buster code
}
since you seem to be already saving the value in this totalDamage variable
I think I understand. Its not being set forever, it just overwrites the default for that one call
I will give that a try. Thank you both
note that you would probably not call Buster inside the Setup method
just set the variable
unless I'm misunderstanding
What is the right way to detect a projectile hitting this shield?
I have a mesh collider on it (picture 2)
But nothing happens (picture 3) which is a script attached to the shield
It just hits the player, never my shield
OnCOllisionEnter is not for triggers
triggers are not physical
What direction should I go then? If you have a tip
Also a MeshCollider is probably too complex here - should probably just use a BoxCollider
or a couple of them
if you want physical collisions you can't use a trigger collider.
that depends heavily on how you set things up
if the collider part of the player's Rigidbody in the hierarchy it will not push the character, as it will be part of the character
unless you did something like give the shield its own Rigidbody
basically - you have to pay attention to how you set up the objects.
Yep yep π. Just to elaborate a smidge further, method parameters are just local variables that we can set externally when calling the method. A way to pass data into a method's local variables.
When the method finishes executing, all the local variables and parameters cease to exist. So they can't store any values in between calls to the method - they must be set anew each time.
thats good to know. Appreciate it
how do i get the DDOL scene?
DontDestroyOnLoad(gameObject);
someDdolObject.scene
they're asking about the scene created which stores all the DDOL GameObjects, not have to make a GameObject DDOL . . .
i assumed it was something like that, and id need to have to ref to a DDOL gameobj
could just throw something in that scene too i guess
you can probably do SceneManager.GetSceneByName("DontDestroyOnLoad")
let me try that
it won't exist unless there's at least one DDOL object of course
yeah i know theres multiple in there by the time i get to this part of the code
do you have any singletons? they're usually DDOL . . .
What is the actual issue. What are you trying to access the scene for? That could help with suggestions
i need to collect all root canvases in all scenes
including DDOL
lol this works
hi i ran into some problems
I want to turn off the collider after the firwst collision
[SerializeField] private GameObject thecolliderthing;
Collider mycollider;
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
//update variable
mycollider = thecolliderthing.GetComponent<Collider>();
mycollider.enabled = false;
Debug.Log("Collider.enabled = " + mycollider.enabled);
}
}
serialize mycollider and get rid of that GameObject variable. then you won't need to use GetComponent at all since it will already have a reference to the correct collider
but also, what exactly is the issue
object reference not set to an instance of an object
do what i said and make sure to actually drag the object into the slot in the inspector
can somone help me
huh am new
Read the link
It says you should never ask if someone can help you
Just ask your question straighy away, and if someone CAN help, they will
oh its just i dont know my sharing game thing dosent work
and most tuts are outdated me and my friend spent 3 hours watching tuts none of them worked
none of them worked
it's more likely you've not followed the tutorial(s) correctly
no there all outdated
What is a "sharing my game thing"
Be as precise as possible
like the unity thing to share your unity project to others
i forgot what its call scm somthing i think
Definitely not
you know this is a code channel, right? and unity's version control works just fine, any tutorial for it will be correct.
well they look different
You have not even looked at all of them. There are thousands
wheres the channel to ask for it
Google up "unity version control" and use the one from learn.unity.com
sorry am not really good at english is that to join the project or invite
I did
can you check over
[SerializeField] Collider mycollider;
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
//update var
mycollider.enabled = false;
Debug.Log("Collider.enabled = " + mycollider.enabled);
}
}
}
!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.
!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.
and I drag the collider component in the object to the script serialize field
and there is nothing wrong with the code. if you are receiving a NullReferenceException then you didn't bother assigning the variable
what does that mean
this would be assigning it
that means if you are still getting a NullReferenceException you did not drag the collider into the slot in the inspector on one or more of the objects with this component attached
wait what i dont get it
What line is giving you the NullReferenceException
a line that is commented
have you made sure to clear the console, save your code, and try it again? because obviously comments cannot throw an exception
then you didn't drag the TMP_Text object into the slot on that component
also 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
β’ Other/None
I did
apparently not considering that is the only thing that could possibly be null in this code
and exceptions do not lie
You cropped out line numbers here
line 16
deathstext.SetText("Deaths so far: " + deaths);
again, that is because you did not drag the object into the slot in the inspector on at least one of the objects with this component
Maybe you dragged it to hte inspector in playmode?
nope
so screenshot the inspector of that object showing it and hte script attached
Then deathstext is null
That is the only possibility, and errors do not lie
add this line to the Update method before the line that throws the error: Debug.Assert(deathstext != null, $"deathstext is null on {name}", this);
It is null
Might be a different object π€·ββοΈ
But it is
Type t:displaydeathtimes in the hierarchy
Because you got an error saying it is
I see (1), that suggest there is more than one of these , is the script on another object too?
if they do this, we'll know for sure
after added the line
notice how the name of that is different than the object you screenshot before
and there are two different object names being printed
the trigger(1)?
so you've got this component on at least three objects. where two of them do not have it assigned
this my respawn code under the triggers
not relevant
you have an object called trigger (1) and one called trigger (2). These have the script on them without the reference being assigned
Doing what I mentioned will bring up the objects
fun fact, you can click the error message with the name in it to see what object it is π
which script do you mean?
the trigger (1) nad trigger (2) only have the respawn code, doesnt have displaydeathtimes code
incorrect. the logs prove otherwise
that's not the name of the component though. you need the actual full name of it
Why did you type that?
that's clearly not true from the logs
oh wait I just checked again, I have deleted the component
sorry guys
If you want help you have to stop arguing. Errors are not wrong.
what do these mean
they mean you have a broken script on some object
you can safely remove it
for example
π im really sorry
thanks for your help guys
Then deathstext is null
Ah, scroll locked. It's been resolved
I thought that was on purpose haha
I have an fbx file as a child of a GameObject, is it now considered a GameObject in terms of accessing it through a script? I can't find any documentation on it and it doesn't seem like a GameObject as although it has components attached it has a prefab field in the inspector.
Nah I was playing DBD and I guess Discord stopped updating in the background due to lack of resources
what does scroll lock mean
Discord didn't scroll down all the way
if it is an object in the scene, then it is a gameobject with component(s) on it.
a scene is a hierarchy of different gameobjects, and gameobjects are just containers for components. so in order for something to actually be in the scene, it must be a gameobject with one or more components (even an "empty" gameobject still has a transform component)
Alright I understand, but what about accessing this prefab field via a script?
why would you need to? also, that's just linking it to the prefab in your assets folder
The "battle map" scene will eventually be created with a JSON file made by the "campaign map" scene, and unless this is a very wrong way to go about it I intended to create all of the 'units' in script from a generic prefab that would have the models and stats attached as it built the battle map.
so the unit has a model that in this case is an imp, but would be swapped for an acher when needed etc etc
okay well that Prefab field there does not exist at runtime. that is something that is editor only to allow overrides to/from the prefab
you get get references to the prefabs you have in your assets folder and instantiate them based on the data in the json file, but that wouldn't be relevant to that Prefab slot you see
now I think I need to instantiate this object with the animator attached in script from a prefab instead of what I am doing now.
thanks for your help
Is C# Dictionary's TryGetValue safe to use if the value is null?
Troubleshooting an error I have and just wanted a vibe check
yes
thank you
yes, but if you are potentially storing null as a value you'll probably want to null check them
yeee
of course it wouldn't be safe to dereference that null afterwards...
As long as the dictionary itself isn't null
id elaborate but its weird niche modding stuff that i would be shot to death for speaking on π
how can i wait a set amount of time to run the next line of code, i have looked it up and found solutions but none of them are working for me
use a coroutine. note that the code that is being delayed needs to be called from in the coroutine, but after the delay
what is a coroutine?
yeah i just looked that up sorry i shoulda looked it up before asking
lmao wtf i just noticed the documentation examples use an infinite for loop in one of the examples instead of a while loop. like i know it's technically valid but that's just so cursed as example code for beginners
why is it trying to say that speed is a double when i made it a float at the start?
it's not
it's saying 1.5 is a double
you can't put a double into your float variable
The value you're attempting to assign it is a double . . .
ah, 20 minutes of google wasted
Look at how you assigned it when you declared speed at the top. What looks different?
I honestly wish numerics were inferred.
You don't want it to be inferred in this case, because there's precision loss.
or rather, you don't want it to be converting double to float implicitely
changed an if statement to a while to test a theory and it broke my unity
Broke..?
cant interact with it at all, i think ill have to close it with task manager
happened the exact moment i pressed shift (its in the while statement) and i can still hear the music
Sounds like a freeze due to an infinite loop.
You could try breaking it with the debugger(assuming it has a simple breaking condition)
seems strange that i couldn't minimize the window or anything though, i just used task manager but im gonna test it again to be sure it was the code
It's weird that you can still hear the music though. That would imply that it's not a real freeze.
Well, when a program freezes, you can't interact with it in any way(including resizing the window). Though it's not as simple as that and depends on the program and the OS as well.
yep the while is definitely the cause, ill just use an if and an else instead
That can be a scary thing . . . π¨
why?
As dlich mentioned, you'd lose precision going from double to float. Assigning back to a `double!+ will yield different results depending on the accuracy needed for the value . . .
good point
While loop and an if else are not really interchangeable though.π€
well google said that getkeydown() was a boolean, so i figured adding a while infront would make it a "while this key is down type thing". instead im going to do it so that if getkeydown () multiplies the speed and else sets it back to its original value
if you get what i mean
Audio tends to be on another thread.
Update is already a loop, so an if on GetKey instead of GetKeyDown is what you want
I'm not talking about implicit casts. 
I'm just saying that a raw number shouldn't have a particular type.
"Freeze your Unity Editor speedrun"
Can someone explain to me what the private set means? ```public abstract class Foo
{
public string Name { get; private set; }
protected Foo( string name )
{
this.Name = name;
}
}```
private means it can't be used by other classses, only within this class
but why would the set be private in the context of an abstract class
To prevent any other classes from setting that property
In this case it's making sure only the constructor can ever set the property
wouldn't the inherited class would be setting it?
no
it's preventing that on purpose
it can only be set through that constructor the way it is written
what I am reading has it used this way, im just trying to understand it: public class Bar : Foo { public Bar() : base("bar") { ... } }
since the constructor is protected, inherited classes can call that constructor
when inherited
yes exactly
this is a constructor on a child class which is calling the constructor on the parent class
this is the only way that the child class can set that property the way it's set up
but the string is still unique to the inheriting class?
I have no idea what that means
"bar"
what about it
The value of the Name property will be set to "bar" here.
that's all
buts its bar.name, right?
No, Name is the property
not name
and I'm not sure what you're getting at with that question exactly
You can do:
Foo example = new Bar();
print(example.Name);```
this will print "bar"
You can also do
Bar example = new Bar();
print(example.Name);
it will print the same thing
How do you imagine that's gonna work? Different number types have different representation in the memory. How is the compiler gonna know how to store that number?
But then how much space would the variable know to take up?
That would of course mean implicit casting behind the scenes...
There is an allocation size that is required.
Unless you want all numbers to just.... take all the space possible every time?
Would this also be for signed and unsigned?
Overload resolution and generics would become major issue
ik this isnt really code but uhhh
if its not code why did you post it here
well where am i supposed to put it
did you look at
How would I make something turn to a random range of rotatinons
Break the problem down.
- Generate a random value
- Create a rotation
- define "turn"
Oh that helps a lot makes me think and i think i got it thank you!
i was wondering if anyone give me any pointers on how i could get it to only instantiate one object but keep it moving all in one script
If I have a prefab that has a script with a constructor on it, how would I go about calling that or can you even?
Components should never have constructors
Constructors are used to create an instance of the type, but it's not required when this type is attached directly to the object
Also, you cannot call it, because, in this case, you're going to create another instance of this class
Which does not make sense
Use Start()/Awake() for initialization instead... Constructors on MBs aren't really supported and will act weird π
So the alternative would be to get a reference to each object instantiated and from there pass along pertinant info like that object's ID or some such?
You instance a new object every frame, because that's how often the Update method is called. You may consider instantiating an object once in a suitable method, like Awake, Start, OnEnable etc.
What is the objective?
Yeah that's a common solution - have whatever instantiates the clone pass along some data to the instance reference. Or store the reference and do it later/elsewhere
a minecraft replica, World class will spawn chunks at locations, but then each chunk will need to know if it's the one being touched, instead of all of them at once
use a coroutine
or make a bool for it
if I'm to use one of those methods wont it'll just instantiate the object then leave it at that since its only activating the code once is there a workaround or should I just instantiate the object and move it in two different methods
or store it in a field, only spawn if null
Well, I'm not sure what you are even trying to achieve?
You seem to instantiate the object, somehow move it, and destroy, all in one frame?
Oh, I now see, it's about timing
Haven't mentioned that float DestroyAfter
You have to create a variable for a Coroutine, which, if null, is assigned to a new Coroutine, which does all this using a WaitForSeconds class
private Coroutine _attackCoroutine;
private void Update()
{
if (_attackCoroutine == null)
_attackCoroutine = StartCoroutine(Attack(10f));
}
private IEnumerator Attack(float lifetime)
{
// spawn & move
yield return new WaitForSeconds(lifetime);
// destroy
}
thank you so much im still learning so this helps alot
I'm learning drag and drop script UI but when I dragged the UI object , it starting to teleport somewhere far away. what am I missing here? (vid and script in file)
No idea what a .mkv file is, but I assume it's some kinda video
idk what other video file beside this... but ya, it's a video showing my problem
So you've just limited yourself to only those that can read that video format to help you. I'd try a mosre standard video format, like one that discord recognizes, mpeg perhaps
ok so video shows what's going on, but you're going to need to post the code outside of a video, see !code for the best ways to do that
π 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.
Your canvas is in world-space render mode and you're giving your dragable item a world-space position of your mouse position which is pixel coordinates of where it is on your game window screen
then how can I fix it ?
Either change the canvas to screen-space, keep the dragable item in the canvas and adjust the anchored position, or transform the mouse screen position into world position
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.UIElements;
using Image = UnityEngine.UI.Image;
public class DraggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
[Header("UI")]
public Image image;
[HideInInspector] public Transform parentAfterDrag;
public void OnBeginDrag(PointerEventData eventData)
{
image.raycastTarget = false;
parentAfterDrag = transform.parent;
transform.SetParent(transform.root);
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
image.raycastTarget = true;
transform.SetParent(parentAfterDrag);
}
}
where should I fix it again ?
i'm dumb sorry
Fix it where you change it's position obviously
OnDrag
Reference your Camera and transform the mouse screen position into world position, docs linked above
after almost an hour, my idiot brain still can't proceed how it can be done right while reading the docs
By the way if you really want to improve your code to the maximum, you could change
if (_attackCoroutine == null)
_attackCoroutine = StartCoroutine(Attack(10f));
Into
_attackCoroutine ??= StartCoroutine(Attack(10f));
```.
`??=` is called the null-coalescing assignment operator and can be used to remove a lot of if statements which check whether a variable is null. It's pretty nice if you know how to use it
Yes I'm a nerd π€
This is your problem.
Input.mousePosition gives the mouse's position in screen space in terms of actual pixels, with the bottom left being 0, 0.
Your image is being sent to the correct position based on that.
But your canvas is in world space.
Oh, haven't thought about that. That's a good thing, thanks for mentioning
but when i changed it into screen space, it either ridiculously big or ridiculously small, and it won't let me resize it, if the problem is my script, I still don't know how to fix it
Ridiculously big in what way? Like in the game view or in the scene view?
Because yes, in the scene view ScreenSpace/Overlay UI can look very large.
Guys I tried everything, i cant enable intellisense, dont send me docs and websites, i already tried everything
The Screen space Canvas uses screen space. It is always huge when chosing Screen Space - Overlay. Try Screen Space - Camera
i have neccery packages and VS code unity ext and c# ext downloaded
Have you tried using Visual Studio instead?
It became very small when i used screen space - camera, I can't resize the canvas itself while it is on Screen space camera
Because it is resized according to the camera
Is there any reason it's not just using Screen Space - Overlay?
when i use Screen Space - Overlay my Inventory UI got lost in the middle of no where in scene and became very small in game scene
It getting lost "in the middle of no where" in the scene view is normal.
Just double click the canvas to have the scene view camera focus on it, and click the 2D button, and you should have an easy time messing with it.
As for appearing small in the game view that must be due to your own scalings.
I wouldn't be surprised if you started with Overlay, swapped to World, and then scaled it way down until you saw the elements.
Mb i just started to get use to this unity like 2 days ago lol
All good.
Set it to Screen Space - Overlay and show the result, and also please show the inspector for all elements in your Canvas Hierarchy.
Like these 3 specifically
i have a system where if the player manages to accidentally deselect the ui and is on controller, it auto selects a pre set button again.
currently i have this if statement:
if (EventSystem.current.currentSelectedGameObject == null)
But Rider is telling me that comparison to null is inefficient. is there a way to do the same thing but in a more efficient way?
if(!EventSystem.current.currentSelectedGameObject)
Objects have a implicit conversion into a bool.
So you can just slap them into if statements where true is when the object exists and false when its null.
I BELIEVE that's what Rider is guiding you towards.
this does the exact same, only (at least to me) it's more annoying to read as it's not the C# way and relies on magical bool conversion which probably does == null internally or calls the same code anyway
Here's a link where the warning is explained - all in all it's BS if you ask me: https://github.com/JetBrains/resharper-unity/wiki/Avoid-null-comparisons-against-UnityEngine.Object-subclasses
It's just an implicit bool operator, which does exactly the same thing as !=, so choosing between them is up to your preferences
omg it worked, finally 8 hours of stressing, tysm <33333
Is there any reason my reference isn't turning up in the inspector???
compile errors
no
you haven't saved? π
already saved, zero erros
ah..
It's just not there π€·ββοΈ
make a change (like add an empy line), save again, go to Unity?
good idea
maybe it hasn't properly recompiled, it does that sometimes
nope
alternatively, make sure Slider is what you think it is
nothing there...
make sure it's the one in UnityEngine.Whatever, and not a local class created by mistake or something
well, I figure even if it wasnt what i thought it was, it would still turn up...
yeah, it is
okay, it randomly appeared now
well, it wouldn't show if it's not something that extends from UnityEngine.Object or is [Serializable]
it's Saturday, Unity is a bit lazy
oh neat, didn't know that
haha, yeah
why is the normal between circles 1-3 unchanging - and hwy does it only change when it grabs the normals of the floor? Am I misunderstanding what hit.normal returns?
Heres the code for the instantiation:
Instantiate(magicCircle, transform.position - (Vector3.up * 0.5f), Quaternion.Euler(hit.normal * 90));
show all the code (in some code pasting site, you know, like hatebin or gdl.space)
[SerializeField] GroundedCheck grounded;
[SerializeField] GameObject magicCircle;
RaycastHit hit;
void Update()
{
if (grounded.grounded)
{
Physics.Raycast(transform.position + (Vector3.up * 0.01f), Vector3.down, out hit);
Instantiate(magicCircle, transform.position - (Vector3.up * 0.5f), Quaternion.Euler(hit.normal * 90));
Debug.Log("Normal: " + hit.normal + "Altered: " + hit.normal * 90);
Destroy(gameObject);
}
}
this is literally it
oh wait
i think im an idiot
Physics.Raycast(transform.position + (Vector3.up * 0.01f), Vector3.down, out hit);
this is wrong right?
I'm more worried about that silly rotation calculation
Vector3.down is casting a ray only onto flat surfaces right?
whats wrong with it?

