#π»βcode-beginner
1 messages Β· Page 55 of 1
Dont try to preview stuff by using the inspector, use the Spacebar to trigger the jump
let me show you a video
I am, I was meaning that the actual inspector doesn't change when I press jump
Or wether im grounded
For your jump: because its only true for one frame, depending on your framerate thats ~10ms
no way you can see that
it works on the bot but not the model i want to be animated
Isgrounded because you only update it on OnCollisionStay, while you are in the air you touch no collider
Yep and for the grounded check, the logic is wrong
Yep
Maybe OnCollisionExit instead
set it to false on OnCollisionExit and to true in OnCollisionEnter
(with a ground tag check)
Though I find physics queries (OverlapSphere, Raycast etc) more robust than collisions for ground check
But you can try that later
Are you sure your model you want to animate has the same rig as your bot?
If the bones are different the animation does not work
Also as mentioned before, the right channel for you is #πβanimation
I honestly dont have a clue why I didn't think of this too begin with haha thanks alot it works perfect
The problem I see with collision-based ground check:
Let's say you stand on 2 floor objects at the same time. You move right, and you no longer touch the floor on the left. This causes OnCollisionExit to trigger and your isGrounded becomes false even though you are still touching the floor on the right
Ohh yeah that makes sense
so use an int instead of a bool
So im assuming the change in the jump bool in the inspector wont be visible when it happens due to it being so quick?
Yes
Alrighty thanks that makes sense
Inspector updates at like 10fps only
Oh damn
Yeah that solves that.
The second issue is that it just usually isn't great for 'game feel'. Having a groundcheck that extends slightly out of the shape will feel a bit more forgiving
And less rapid changes
Hello ,
I trying to do a camera wobbling , when the player move and when the player sprint
my problem is when I change the offset of the visual camera it shakes a lot , so is there any way to remove it ?
public void ChangeCameraWobbling(float zOffset, float amplitudeGain)
{
virtualCamera.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>().m_AmplitudeGain = amplitudeGain;
virtualCamera.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>().m_PivotOffset.z = zOffset;
}
this is my code and here is a vedio of it
how can i animation cancel? for example if my roll animation is 30 frame but if i jump stop the rolling and start jumping animation? im using currently animator + triggers via c#
transition with a trigger and no exit time
i unticked the exit time, care to explain me this transition thingy?
with exit time you can only exit at a specific frame
without you can do it anytime
but that only works with a trigger
or do you mean what a transition is in general?
i think i got it, thank you.
i have a soldier with empty game object at the end of gun but when the soldier(parent) rotate the game object(child) doesnt
Hello there. Can someone help me about this error? This error doesn't affect anything in the game's functionality, but I don't know what it means and I don't really understand what it says. This error only appears at the beginning of the application execution. If I close the unity editor and open it again it disappears, but after a certain amount of programming time it appears again.
Does it move with the tip just not rotate?
it moves together with soldier when i rotate him and move him but doesnt rotate itself
Unity Editor bug, nothing you can do
i rotated the guy but the object doesnt
whenever i try to open unity hub it says there is a critical error quits. would you be able to help me?
anyone be able to help me*
Ah I see. I've been doing some projects to train and I thought there was something wrong with what I was doing.
Thanks
which hub version?
Do you have the pivot on world space maybe?
latest
like here?
revert back to 3.5.2. I posted a download link for it a few days ago in #π»βunity-talk
ok thank you
ok so it was rotating but i couldnt see it
yes, most likely
should i keep it pivot and local
you can stick a 3d object on it
to see if it rotates
usually you wanna keep it global
it rotated when i selected it with "Rotate tool" on scene
ive scrolled back on your last week of dms and cant find it
would it be possible for you to send another link
For some reason it doesn't fetch the object reference. I cannot find why.
There is one object in the scene with a Level script
is it active?
Yes i think so
or yes
it is
Its being referenced by other objects. just this one that doesn't want to
then you need tp provide more context. are you certain that line of code is running? are you certain it runs after the Level object has been created/activated/whatever?
also if both objects exist in the scene at edit time you're better off just serializing a reference to the object directly instead of using Find
Oooh okay i found the problem. I put the reference as public. to give access to inheriting classes. How do i give inheriting classes access to the reference without putting it as public. Or should i not do it like that
protected
inheriting classes can access public or protected members
but i also don't see how it being public makes it not work
are you sure that is what fixed it, and not perhaps just saving the code and compiling some other change?
My guess would be on a race condition with random outcome π
which object loads first
Might be that. but now i know protected is a thing so ill use that π
So I'm trying to instantiate a projectile and have it move in the direction I'm facing... I haven't figured out the facing part, but my projectile doesn't move at all. Im doing the following, and my projectile speed logs at 4, and my transform.forward logs as (0.00, 0.00, 1.00), but when I multiply them, my velocity is (0.00, 0.00). What am I doing wrong? float projectileSpeed = projectile.GetComponent<ProjectileBehavior>().projectileSpeed; Debug.Log($"Projectile speed: {projectileSpeed}"); p.velocity = transform.forward * projectileSpeed; Debug.Log($"Forward: {transform.forward}, Velocity: {p.velocity}");
you're gonna need to provide more context. is this 2d?
Sorry, yes. This is 2d. I'm pretty new. What context can I provide to help?
well that's why it doesn't work. transform.forward points forward along the z axis which is just used for depth.
what is p?
p is a RigidBody2D
you probably need to use transform.right or transform.up depending on the rotation of the object when it is not rotated
Ahhhh. Okay. I tried transform.right, but I think the projectile just stayed there too. But let me try again.
i atached camera on top of my player but i dont want it to rotate when i move my mouse around how do i do it
don't make the camera a child of the player
use cinemachine and just make the camera follow the player but not rotate with it
Ugh. That was it. Thank you. π Is there a good way to get the facing of the current sprite? Or do I need to save it as a variable and change it anytime we change direction?
cinemachine?
wouldn't it just be easier
every frame just reset camera rotation to 0 0 0
if you are only flipping the sprite and not the actual object, then you'll need to track where it is facing manually. if you rotate the entire gameobject then you can just use transform.right
I definitely don't, and it just shoots to the right, regardless of facing, so I'll have to keep track of direction and rotate manually. Thank you!
i mean, you can try that. that doesn't mean it will be any good though. you're better off just using cinemachine if you don't want shitty camera controls
how to use it and what is it
i will just google
transform.rotation = Quaternion.Euler(0f,0f,0f);
i started unity yesterday that's good enought
i mean okay. but you should still learn how to use cinemachine. it's an incredibly useful tool and you won't end up with stuttery/shitty cameras
I'll google.
i will
That was easy. π
Boxfriend just suggested cinemachine 2 weeks ago to me, it was like switching from a toyota to a lambo, you will thank him later π and i was using the old camera system for 3 years before
i want my game first to wark later to look
i like programming more
cinemachine works better, it looks the same by default
old camera is basically dumb and you have to do everything by hand, cinemachine you tell it what to do and it just does
just beware that having your camera as a child of your player is even worse than just writing your own camera script for it. it's rotation and scale will also be affected by the player. and if you are moving your player with physics you'll end up with a very stuttery looking camera (though it will just appear as if your player's movement is what is stuttering)
now itry to make a background
and i have rock texture and it worked in 3d
but i dont know how to put it on 2d sprite
Would anyone know of any guides/tutorials on how to do vertex displacement through code (not shader), ideally for a sphere please? I've had a look around but everything I've found is shader based, which won't work for what I have in mind. π
Look for sebastian lague
he has a series where he makes a planet
Yeah, I'm looking at his planet generation stuff atm, but tbh I'm a bit lost translating what he's doing with noise toi using an image instead.
Convert the texture to a Sprite2d
click on it and you can set the type at the top
ok and how do i make the pattern repeat or do i have to put 100 10x10 sprites to make abckground
well you can just put a plane in your game and apply the texture to it
instead of a sprite
I just switched from doing individual keypresses for movement (WASD) to using Input.GetAxis() to get whether someone is pressing a key... I've noticed that it went from being very precise movement to there being a 'cooldown' where the axis is still going from 1 to 0. Is there a way to avoid that and instantly have it hit 0 when I stop pressing a button?
or switch the image type to "tiled"
Use GetAxisRaw. GetAxis uses smoothing
Perfect! Thank you!
later would it be possible to add ability that i move UP the 2d plane temporary change character to 3d so he can see other from above as walking sprites on sheet of paper and shot them
certainly possible
but not a thing we could just explain here
thats a multi step process
can you change camera of a player with script mid run
that's even easier with cinemachine
oh yes
the camera is lagging i am learing it
tutorial said i should have cinemachine up here
i dont have it
Go to windows -> package manager
i see
and there in unity registry search for cinemachine
even if you have the package it's not up there anymore. you can create cinemachine objects from the regular Create menu.
oh right π
no need for that
just rightclick in the hierarchy and it offers you to create everything you need there
can i reduce the delay with movement
what delay do you mean exactly?
probably means the damping for the camera
yeah reduce the damping on the vcam
how do you reduce it
change it from it's current value to a lower value
you should go through the documentation pinned in #π₯βcinemachine to learn how it works instead of asking for every little thing
What should you expect in a script, when you call transform.parent? I assumed (incorrectly) it would be the parent of the current script?
it would return the parent transform for this component's transform. if the object has no parent it will be null
Is there a good way to get the "main" object this script is attached to? Ideally, I'm trying to get a variable from another script attached to the same object.
what do you mean the "main" object?
So I have a Player Gameobject, and attached is two scripts. I'm trying to get a variable from the other script attached to the Player object.
if it's the same object it's just transform or gameObject. or you can just call GetComponent to get another component on the same object
you would probably benefit from going through some beginner courses to learn how to use the engine. i recommend the pathways on the unity !learn site
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thanks. I'll take a look as soon as I figure out how rotation works. π
should i weapons base stats be held on the scriptable object for it?
or how else should it be done instead
still having issues anyone got any suggestions?
this is a code channel
As you were told before. Not a code question. #π»βunity-talk
ScriptableObjects are good for base stats. You want them generally to be unmutable, and store the mutable data like current stats in a class (monobehaviour or poco)
why r u buggin
What? I'm just pointing out that you have been told multiple times that this is the wrong place to post that.
You're welcome
So I can see the facing, and I can see the euler angles, which go like 0.00, 0/90/180/270, 0 but my projectile always only shoots right. If I'm facing up or down, it doesn't shoot at all. What am I doing wrong here? Rigidbody2D rigidbody = projectile.GetComponent<Rigidbody2D>(); Rigidbody2D p = Instantiate(rigidbody, transform.position, transform.rotation); p.transform.eulerAngles = transformProjectile(); // This returns the vector3 Debug.Log($"Euler angles {p.transform.eulerAngles}"); float projectileSpeed = projectile.GetComponent<ProjectileBehavior>().projectileSpeed; Debug.Log($"Rotation {transform.rotation}"); p.velocity = transform.right * projectileSpeed; Debug.Log($"Forward: {transform.right}, Velocity: {p.velocity}");
are you actually rotating the object this component is attached to? or are you only rotating the sprite?
Hrm. good question. I think I'm rotating just the rigid body.
that would rotate its transform (on the next physics step). if this component is attached to that same object or a child object then it would rotate with it
Hrm. No, p is the instantiated projectile... Rigidbody2D p = Instantiate(rigidbody, transform.position, transform.rotation);
So that should rotate the whole thing, shouldn't it?
well the projectile would be rotated to the same rotation that this object is rotated to, yes.
I updated my code above... If the euler angles when I'm facing right are 0, 0, 0 and when facing up, 0, 270, 0 and facing down, 0, 90, 0 and when facing left, 0, 180, 0 shouldn't that rotate the projectile that's instantiated?
why are you changing its rotation immediately after instantiating it with a specific rotation? just give it the correct rotation when you instantiate it
Oh. That would make more sense.
it will also not make a difference as to whether it is rotated or not and has no effect on the velocity since you are using this object's rotation for the velocity, not the spawned projectile's rotation
oh. because I didn't know how to go from a vector3 to a qquaternion. π
why do you need to?
and again: #π»βcode-beginner message
Because when I change to this: Rigidbody2D p = Instantiate(rigidbody, transform.position, transformProjectile()); it says to use a quaternion, and it can't change from a vector3 to a quaternion
but what does transformProjectile do
how do i add velocity in direction object is facing
It looks at the player's facing, and returns a vector3 based on that facing.
And that vector 3 is 0, 0/90/180/270, 0, which is obviously wrong. π
instead of showing all these disjointed snippets can you share the whole fucking class so that i don't have to play 20 questions to learn wtf your code is supposed to be doing?
is it possible to write you own mesh class and custom mesh shader/renderer ?
Transform.forward is that direction
only in 3d π
Sure. sorry. I was trying not to flood the channel.
transform.forward += 1; for example?
!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.
this line makes no sense
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
return new Vector3(0, -90, transform.eulerAngles.y);
why are you putting this object's Y rotation as the z rotation?
This would be the equivalent if you told me that you are looking east, and I told you to add 1 to that.
Basically check what is the type of the variable you're trying to modify (and if you even can modify it)
@slender nymph Because I'm an idiot. :/
i'm trying to render a voxel world using cubic chunking (32x32x32), so what that means is i can do away with the float-level precision for each vertex of an individual mesh, i only need 6 bits per axis to describe the position of any vertex in a chunk mesh relative to its chunk
issue is, unity meshes uses floats to describe their chunk positions, and shaders follow that by taking in floats from the datastream
i dont need float, i need a single byte per axis, or just 18 bits to describe a vertex position, + 1 float4 for the chunk position relative to the world origin
okay. changing it to return new Vector3( -90, transform.eulerAngles.y, 0); didn't make a difference. I'll go watch some unity videos first.
@slender nymph thanks for your patience.
I've thought of two solutions for this:
- write my own mesh class
- leave vertices and triangles empty for a default unity mesh, and instead utilize a TEXCOORD to stream in my custom data
I'm tempted to go with option 2 cuz it sounds much much easier but i don't know how much memory waste that'll entail
so i'm not too sure what to do, i have no experience with meshes or shaders so i might have things completely backward
would this still work if items could be upgraded and stats on it increased?
Yeah, you wouldn't be increasing/upgrading the SO though, you would do it to the "current" values in the class
You could even make the upgrades ScriptableObjects though
yeah
your welcome for what? bro thinks hes a mod when im only asking for help on a simple fix
is it bad that the stats manager is cluttered at the moment with a lot of variables going around?
it feels a little clunky
and bad to look at
This.... is.... the wrong.... channel.
There are 5 mods and 21807 people online.... so yeah, the residents (and all community members really) try to help out.
follow channel rules, no ones gonna answer your questions if they're asked in the wrong channels
Doesn't need to be a mod to remind other people to follow rules
Well.. if you feel like there's too many there, you can try to separate it into more specific stats. You can use a POCO and have the StatManager have subclasses like the HealthStats, OffenseStats, etc.
But really, there aren't too many there. Looks fine to me
alright, im just new to coding and always curious if im going overboard on something simple
but i am having an odd error and im not sure what it is
https://hatebin.com/wnzfmmttyj - slot manager
on line 15 it says object is not instanced if an item slot is active
Yeah, that can be a double-edged sword. I would say just try to get it working, and don't be too worried about refactoring later.
https://hatebin.com/lpaesrfgbc - the quick bar slot
my 2nd time ever using properties so i mightve made a mistake
nobody answers any questions in the correct chat, so i went to an active channel for advice.. do not think this was unreasonable at all
sure, but you were a bitch about it
What is the error?
Btw, color values are between 0 and 1. In your case, it won't make a difference (because it was max values anyway), but if you wanted it a precise color, either use decimals between 0 and 1 or Color32
and still, not the correct place, continue asking in the correct channels or searching it online
Well.. it was
Provide more info and maybe someone would help?
All I saw were screenshots
theres not much more info i couldve provided
Ok... lmfao
Maybe the logs????
oh thats just cause of the slots have a white square and it annoyed me so i made them either transparent if nothing there, or fully parent if theres an item
what r u on about
bro if people are wiling to help why not just provide the right fuckin stuff dude
There are... logs. They tell you why things happen... Google it
ask where to gettem if you dont know
the error is that its saying NullReferenceException: Object reference not set to an instance of an object
QuickBarManager.Update () (at Assets/QuickBarManager.cs:15)
in unity
not the compiler
but im not sure how it would be getting that
its only when a slot is active and it has an item in it
Hi guys, I have a Player object and a gameobject that will be "collected" if a certain part of the player object touches the gameobject. I've added Colliders to both and marked the pickupObject as 'trigger'. On the player object, I have two colliders, one to act as the physical "body" of the character and one to act as the point that will be used to "collect" the pickupObject if it comes into contact. However, no matter what I do, I cannot seem to get this to work. It either triggers on the body and not the top, or none of them at all.
Ok yeah. That's a runtime error, so it wouldn't show in the compiler. Can you show the inspectors for the Quickbar
yeah
the manager or the actual quickbar slot?
statsBasedOnHeldWeapon is null probably (you never set it to anything)
The QuickbarManager
Eh, and one of a Slot
So, your issue is that you want the collider used to collect to be the only one that triggers the pickup?
Yeah
slot icon is the slot, i need to rename it
Yeah
Are both colliders on the player NON-Triggers?
Yes, I've tried making one a trigger and both non-triggers but either way it didnt work
So, I see it says None in the ItemInSlot box
yeah but if i fill it in, it takes itself out
Both need to be non-triggers. And both colliders are on the same object? Or is one a child?
when played
hold on
i know what to test
Both are currently non-triggers and both are on the same object yeah, one under the other
if (QSlotReplica._itemInSlot != null)
{
_itemInSlot = QSlotReplica._itemInSlot;
}
This should probably be == null not != null
Can you show the inspector for the player? (show the whole editor, don't crop it)
Okay
i think its cause its trying to set the quickbar on the normal screen, but not inside of the inventory where you can put things in the quick slots there
it should just be replicated from the inventories quick slots
I originally had two box colliders. (google suggested mixing the colliders and checking for the type of collider to determine the "correct" collider. This hasn't worked since now the Box collider never triggers when the pickupObject comes into contact with it but the polygon one does which is the opposite of what I want π
Ahhh perhaps the polygon debug message is actually the pickupObject's polygon collider?
If you used other, that would be it. But if you don't use other, it wouldn't be.
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.
Sorry I'm not sure what you mean. There's also no code besides the code I posted earlier, it's just inspector components. The pickupObject has a 'polygon 2d' collider which is marked as a 'trigger', the playerObject has two colliders, one is polygon and one is box collider. Both are not marked as a trigger but one is acting as the "body" of the player, the other collider which is a box, is above the body collider so that if the pickup object touches the "top" of the player ( I guess like a headshot in a FPS game?) it will then trigger and "collect".
however in my testing, I cannot seem to achieve this. The pickupObject is triggering both the player colliders and I can't find a way to separate them
Oh, I missed the code you posted earlier I guess. I wanted to see the CollisionController code. I don't see that posted above
other is the parameter passed by OnTriggerEnter btw
Also, it would have helped to see this uncropped, as I asked. You cropped it to only show the inspector
okay I edited my post as it was slightly wrong, that's the current situation ^
and I can repost code no problem
oh sorry I thought the other bits were not importnat
a moment π
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("OnCollisionEnter2D" + col.GetType().ToString());
}
void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Type: " + collision.GetType().ToString());
}
One sec, lemme do that agian so its easier to read/se
Ah yeah, OnTrigger2d's parameter is defaulted to collision. Sorry, that's what I meant by "other" earlier
These are still cropped to only show the inspector..
OHHHHHHHHHHH you want the 'scene' ?
I want the entire editor
every single thing on the editor
Haha so sorry I misunderstood
Okay is that it? π
You can see the little green hollow box at the top, that is the point in which pickupObjects should actually trigger and "collect", but not the polygon (body) of the playerObject
Yes, ok that is perfect.
Now that I can see what's going on, I can difinitively say you want the top part to be a child object
I see
How might I do that? do I make another emptyGameObject and then attach the collider there?
You would make a new empty game object and make it a child like you have the GroundCheck and SkyCheck
Yeah, okay I get it now
what is SkyCheck btw? That seems like a good thing to use for this purpose
This makes so much sense now.... I can see why it was not working before.
Yes you're right SkyCheck would be ideal for this
how bad are particles for fps
can i create a custom mesh class whose vertices have custom data? I know about TEXCOORD data but I'm trying to reduce the number of bits per vertex from 4 bytes per axis to 6 bits per axis, and I'm not sure how else to do this
as long as its reasonable, afaik the unity particle system is efficient
not a major impact
One more question, somewhat unrelated. How could I make it so the playerObject collider is "strong" and pushes other colliders (objects) out of its way as it moves around with no loss of "movement" ?
so i have 2d game and bullets are very small and i want them to glow
do you want it to be rigidbody
Yea
you can just put mesh colider without rigid body so it won't be able to be pushed back
i think there is mass option in rigidbody
Kinematic rigidbodies will be "strong" and dynamic will be "weak"
Kinematic ones don't respond to forces
or you can give them huge mass and they will react very little
Thanks guys , much appreciated π
Yeaaahh... that will have some consequences, but it's ok
i started yesterday
I'm working on a 3d game and trying to get the hang of unity. When I move and look around my game objects in the scene, it looks like stop motion instead of the fluid movement and im not sure whether this is a camera, or movement issue, or if its something else.
Might be a little hard to see in that video
if i make a prefab and then change script will script of prefab also change?
Change script in what way? The code itself, or you modify some values in the Inspector?
If it's on the scene and you add a script it wont unless you click in the inspector to apply changes to the actual prefab asset instance
otherwise open up the prefab editor window and apply the script
The things you touched compared to a prefab will be in bold, with a blue bar on the left of the Inspector
the script used for the prefab
That does not answer the question
I'm trying to store vertex positions for my mesh in an optomized manner, so does anyone know of a way i can my per vertex position data in a TEXCOORD while leaving vertices[], triangles[], and all the other datastreams empty?
Code changes are applied everywhere
for example i change varaible speed
so does prefab get coby of the script or will the prefab change how it works when i change the script
In the code or on the Inspector??? We'll get to it one day I hope
in project files
That's not a valid answer lmfao
- Code
- Inspector
Choose 1 or 2
i think code
You think?
noncoalesomething does work in non-unity objects right?```cs
Shop toedit = AllShop.FirstOrDefault(shop => shop.shopID == ID) ?? AddNewShop();
No
Ah, non-Unity objects it does
https://docs.unity3d.com/ScriptReference/Mesh.SetVertices.html
Through the mesh class?
tis either code project.cs or what inspector for sure not inspector so it has to be code
The Inspector is the thing on the right that shows the Transform, where you can add scripts and change their values
or, my other solution is to figure out how to write my own mesh class with my custom data
then figure out how to write a shader for that custom mesh class
i mean the project.cs script
that stuff
but it sounds a lot easier, if it's possible, to kind of use the existing mesh class as a husk that doesnt store any information in its traditional fields, and i route all my custom packed data thru TEXCOORD
probably not inspector
Okay so the code.
Code changes are applied automatically throughout the entire project
wait
is this exactly the function
yes, there's new advanced mesh methods which you can just use the vertex buffers directly
i was praying to the lord
exists?
ok, im not at all familiar with the lingo, like i'm not sure what exactly thatmeans but I'm pretty sure this is literally exactly the thing i was looking for
thank you so much man
so is this the "husk" thing i was talking about where it basically pretends there x number of vertices ?
yeah, the difference between these methods and what the mesh class original has is you can pass all variables at once, instead of position then triangles, ect
I mean, this is like peak optimization if it matters I guess
thing is im creating a voxel world
so having so much precision is worthless for that
i saw a video where someone packed 96 bytes of per-vertex data into just 4, and it makes a lot of sense
but they did that in opengl, was trying ot figure out how to translate that into unity
Right, you can probably just compute it all directly instead of using unity's API (or rather access the graphics API without going through too much of unity's API calls)
can you set a custom data type with this i wonder?
i guess it doesnt matter, since i need 4 bytes only
and that neatly packs into a float
i can probably work with that
Oh, I thought it had indices/triangles too. Huh
I forget this stuff a bit
Also this:
https://docs.unity3d.com/ScriptReference/Graphics.RenderMeshIndirect.html
To render multiple mesh datas at once
here is my full code: https://pastebin.com/1P7gPrTM ,
Hi I am trying to use the new input system for my jump code but it keeps giving me this error: NullReferenceException: Object reference not set to an instance of an object. I am doing it just like the example in the docs, so I am confused. does anyone know my problem?
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.
what line
48
quick question about Mathf.Approximately(), is a variance of Mathf.Epsilon really "big" enough to account for floating point shenanigans?
if (playerInput.actions["Jump"].IsPressed() && _groundedPlayer)```
Quite a few things here, so I suggest you to debug log each of these such they are not null and then maybe you can find yourself the answer.
That function is specifically made to handle floating point shenenigans
Breakpoint would be better since it's in update, but otherwise make sure playerInput is set in the editor
Depends on whether the numbers are close to zero or not. If not, it applies an epsilon of 0.0000001
Check out the source code for that implementation
istg ive seen floating point funny moments higher than epsilon
Definitely, the bigger the value, the higher the error
are you saying there are multiple things that i am doing wrong?
but Mathf.Approximately still returns true for these cases?
or am i misinterpreting the methods functionality
Yes, it does
It means that if you've a lot of accessing or checking in a single line and that's where your error is, then you may not get the exact error of what was not set.
So what you'd want to do is check each individual operation you're doing, starting from the first.
ok just making sure bc i have while loop anxiety lol
ok i fixed it, thanks for the help
Oh, does it? I still don't trust it enough ;)
me neither, esp as a while loop condition
yeah what the hell unity
these 2 things sound like they should be swapped
programmers cannot name things ig
well just in case ima make an 'emergency exit' in the loop lol
I have a parent script that a few different children scripts extend. Is there a way to find all of the different scripts that extend this parent inside of the scene? like looping throughGameObject.FindGameObjectsWithTag("ParentTag")and than using GetComponent<ChildScript>() for all of them, except the child script's name will all be different, their only similarity being they all extend the Parent script.
The parent script could have an enum that would be the type of the child, then you know what to call GetComponent as. Or there is reflection.
But maybe say what you're trying to do, because this seems like an XY problem
Trying to deactivate every child script in the scene
For a game over sequence basically
What do you mean by "there is reflection"?
Then why not just deactivate the parent objects? Or do you want all the NON-inheriting classes to remain active?
You should google reflection, but it's costly and not great to use
I can't deactivate the parent objects because of the models attached to them
So, you want to find all objects that are child classes of some specific type?
Yes
Oh, I thought you were using that to start with. I see now it was by tag.
Sorry lol
All good, I appreciate it
If you also need to filter by tag, better to search by type first, then iterate through and check the tag
Just make sure to use CompareTag not == to check the tag
https://pastebin.com/twB49GcZ
I made a code that moves a slime to a certain position and then slowly moves them to another, choosing one of three colors. my problem is that while the slime is in fact moving, it doesn't seem to be affected by the moveSpeed variable, even if i change it it's still the same speed
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.
Do you change it in code or in the inspector?
in the code
The inspector will override the initializer
Change it in the inspector or set the value in Awake or Start
i see, thanks for the answer, it should work now
hey, does this forum only focus on unity 2D/3D or also VR?
there's an entire #π₯½βvirtual-reality channel if you have a question that is specific to vr
yeah was wondering wether that is for code questions aswell or just general VR question stuff
thank you
y
Hey, i can ask a question here ?
yes
Here is my game when i start it instant with the level, and after when i use my menu to start the level, why my luminosity is so different ? idk how to fix that
This has something to baking light
Even if not baked you should hit the bake button in lighting tab
i just found :), ty
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent<Goal>(out Goal goal))
{
SetReward(+1f);
EndEpisode();
}
if (other.TryGetComponent<Wall>(out Wall wall))
{
SetReward(-1f);
EndEpisode();
}
}
could someone tell me why im getting this error?
The type or namespace name 'Wall' could not be found (are you missing a using directive or an assembly reference?)
im getting the same error with 'Goal'
Wall and Goal are 2 3d objects I have with scripts 'Wall' and 'Goal' which are empty attached to them
Share the Wall script.
Its empty
Doesn't matter.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallCollision : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
oh
i see
It's not a Wall
do you mind explaining what the things you input into if (other.TryGetComponent<Wall>(out Wall wall)) mean
like why do I use 'Wall' and then 'out Wall wall'
You can read more about the method in docs:
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
To put it simply, TryGetComponent is a generic method that takes a generic type and returns true/false depending on if it has found a component of that type on the object. If found, it outputs it in the out parameter.
You don't need the <Wall> part
And you can do (out wall) if wall is already a declared variable
Wall wall;
if (other.TryGetComponent(out wall)
Would work too. Declaring it separately doesn't make sense if it's local. It's more for when it's a class variable so you can use it in other methods or classes
Might be confusing for first timers how it works especially when C# lets and prefers you to automatically cut down what can already be said implicitly.
Ah okay I think I understand
The thing between the <> is the generic type argument, it's basically how the entire method operates as whole based on the type since it can dictate what type arguments or what it returns, depends on how they make the method work.
The out keyword is just another way to return a value from a method, since the method already returns a bool (true or false).
The Wall after out is the type of the argument. Noticeably, the type changes based on what's inside the <> or the generic type parameter.
Like he said earlier, you can cut down the thing inside the <> because C# already knows what the generic type is based on what you put in the arguments alone.
If you hover on the method the tool-tip should show TryGetComponent<TComponent>(out TComponent wall) where TComponent : Component or somewhere around that at least.
I've been trying for a while to do it on my own without help or searching and nothing seems to work, would anyone be able to point me in the right direction of making the player movement follow where the camera is facing i've got another script handling the camera
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
And this is the camera script
Ohh wait I'm guessing my mistake is not rotating the character on the horizontal axis with the camera π
Hi, need help with using unity for simulations
Basically the plan is to have NPC(s) that navigate the world based on slider settings (how much of the traversal journey will involve running, jumping, etc.)
The end goal is to use some type of ingame camera to record the pathing or resulting world interactions that said NPCs have.
What unity libraries or workflows that can be used for this?
why wont even the debug show up?
the update is early return
that means you cant grab weapon once the current weapon is null
thx
Why if I do something like this so I g et an error? I'm checking for existence, and it's possibly undefined, but possibly defined? int x = 1; string myWord; if (x == 1) { myWord = "Hello, world!"; } if (myWord) { Debug.Log($"My word was {myWord}"); } It tells me Use of unassigned local variable 'myWord'
What if x isn't 1?
set it to "string.Empty" when you initialize it
Then myWord should be undefined and it won't go into that if block?
It WILL go in the second though
@brazen narwhal This was actually something I found out when I was trying to debug a problem with another class. The real class is SpiritBehavior, which I can't set to string.empty π
oh ok
@summer stump Is there a different way to check for definedness?
myWord would be null, if x wasn't 1. Right?
So it wouldn't go into the second if?
Then you should still set it to something
Or do I not understand C# at all (which is quite possible, I'm very new to it)
@polar acorn Can I just set it to null??
the error is just that the variable is undefined, so you have to somehow define it as something
There is a difference between null and undefined. Undefined cannot be checked for, because an undefined variable literally does not exist. It's not a pointer with nothing in it, it literally does not exist to check
yes
There's a difference between an empty box and the abstract notion of a sudden lack of boxes
That makes sense.
this is actually a great explanation of the difference
I'm coming from a different language, where there is a difference between undefined and null, but var something; is null. Although, now that I think about it, I'm not 100% sure I'm correct.
Player.transform.localRotation = Quaternion.Euler(0, turn.x, 0);
how can I make it so that it only rotates the x
(basically get rid of the 0s)
@brazen narwhal @polar acorn That is a very good explanation, and i really appreciate it.
C# actually does the act of allocating memory for a pointer when you assign a variable. This means a variable that is never defined but also never used doesn't take up any memory
yea it really depends on the language
Ahh. That makes a lot of sense, thank you.
I'm coming from node, where everything uses memory (not really, but it was funny in my head...)
some coding languages set variables to null when initialized
Ones more user friendly ones more memory friendly
yea
It makes sense. and If I wasn't writing code at 1am, I'd like to think that would have been obvious to me. π
usually higher level languages do that
I also didn't realize it's 1am. Thank you again, both of you. I'm off to bed.
gn
Can I make an OnPointerEnter work in this tilemap(white thingies)?
omg silly forgot to send the screenshot,
PS. the error is irrelevant btw
I can only think of Lua for this.
Considering nil is another term for null.
For Javascript, I think they use undefined by default.
string.Empty user versus "". 
how do i take a look at available overloads for any function/method on the user interface ?
i am using Visual Studio 2022, default keyboard shortcut settings.
TBH, just type out the method, type a , inside the method parameters and u should see an arrow that you can scroll up and down to on the tool-tip.
That's how I've been doing it.
Type it to to the parenthesis and inside you'll get a tooltip with numbers like 1/3. At that point you can use up/down keys to switch between the overloads.
You can also f12 the typed method to find it's definitions.
Lastly, there are docs.
Hello, does anyone have a level changing script I could look at?
I tried a few and they all fail to work, but visually code goes through
This is what i used for my first game, very basic in nature.
Don't forget to enable the scenes in your Build Settings.
you make a method that changes scene from level 1 to level 2 and then you call that function upon a button click, or any other triggers
since you created the strings, GAMEPLAY_SCENE and MAINMENU_SCENE, use those inside the SceneManager.LoadScene();
and after that you have to use "loadMainMenu()" or "restartGameplay()" on a button click or other trigger
how do I manage to do that?
how do you intend to change the levels in your game ?
I have an object I can create
is it by click of a button or character dying, etc ?
walking on to a platform
then you need to insert the loadMainMenu or the other function into the OnCollisionEnter2D or OnTriggerEnter2D depending your game
no, just insert the restartGameplay() into your Collision function
so that when collision takes place, the level 2 scene is loaded
you usually have a OnCollisionEnter in your player script, or in the platform script on which the player will walk at some point
i dont see it
then you need to create it
ok can you help me with creation?
no, unfortunately. Don't have much time.
sure
May I suggest that you follow some tutorials from !learn because you seem to be lacking a lot of very basic knowledge
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
how do i check for collision when the object isn't projectile for example i want to make laser but make it stop when it hits wall and dont come out from the other side
because it is not flying i cant check frame by frame for collision but i have to check have there been any object on the path of the laser and if there were few i need to find that was first and change position of laser end to this of an object
i could make small invisible object fly at very high speed and when it hits something it will ge me anwser i just thought of it but then there will be little ddelay
and if wall is thin is it possible the object will miss the wall between frames if it moves too fast?
Sounds like you may be looking for a Raycast: https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Which will fire a invisible line in a direction and store everything that was hitt along the way into a RaycastHit array, theres also a "NonAlloc" version of most casts which let you control what gets returned, and all casts work best using layers to filter unwanted objects along the path - there is also a "LineCast" if you know the end point of your laser, which will stop at the first thing hit, however all of them rely on the thing your hitting to have a collider to be detected - there is also Physics2D that offer similar functionality if your game is not using 3D objects/collision
ive also got a question
how do i make a tight 2d player control with colliders because wall clipping is an issue and using tilemaps makes corner blocks hard to use
ive got a ground check hitbox below to check for ground but it clips into the wall and gives an unintentional wall jump
i am usint transform.psotion to move my character 2d. but i use rigidbody to detect collision so it pushes me back when i try to go thourgt wall. so i could use velocity to make dash for my character i could use velocity but because gravity is set to 0 the velocity never stops and i move in that direction all time is there a way to slowly negate all velocity like here
so when someone pushes me or i dash the velocity fade away for example in 1 second
help this guy first ^
hey guys, does unity have a built-in method or feature to show in the screen a timer? Like appear in the screen a timer 10 minutes and it decreases every second until 0? or it needs to be done 100% via code?
hi everyone, trying to create a 3d movement system from scratch but im stuck, i got the player rotation with the camera but it still moves in the same direction, im trying to get the player to move in the direction of the camera, any help please?
Well, what do you expect to happen?
You're moving the player using horizontal and vertical input, not including the rotation anywhere
You could take a reference to the camera transform and use it's forward and right vector
i got it nvm just switched that out on the player movement to follow to camera direction!
do you know hoe to fix this though, only lets me jump to a certain height then falls slow
No idea, I rarely ever play around with physics
Play around with the mass and jump force
can i change the refresh rate of Update() function?
Update is called every frame
no, it is based on the execution time of your code
You could play around with either Coroutine or InvokeRepeating
and can i ```cs
timer = 0;
in update->
timer + Time.deltaTime;
if(timer > 0.05){
timer = 0
// here you do what you want the function to do
}
will taht work?
More or less, yeah
unless someone have 5fps
that is basically what FixedUpdate is for
I feel like I'm having a really stupid brain fart right now...
I cannot get my floating head boss to register collisions with the walls.. boss has a poly2d trigger collider, floors and walls all have box colliders.
Neither ontrigger or oncollision will register vs the walls, but trigger will register vs the player. I didn't think trigger required a rigidbody to interact
all collision/triggers require a Rigidbody
and ```cs
void FixedUpdate(){
}```
is premade function of unity same as Update?
is there good course? where i can learn the basic of unity?
yes
thanks
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
WoW that is a lot
I have a bunch of GameObjects stores in a Dictionary variable. Instead of searching through the Dictionary, I was wondering if there is something I can add to the GameObjects, like a reference number, so I can match it to the correct dictionary entry?
dictionary is unordered and you retrieve the gameobject by key
I'm not sure if I understand but I have a idea for that.
if it's a runtime only dictionary not to be saved then use GetInstanceId()
I have an issue in my game when my score is 20, i need 120 points for 3 stars but its saying i have 3 stars π₯
Show your code, perhaps your conditions are backwards
Yeah they're backwards
The first one says "if 120 is greater or equals than your score"
It's most likely always the case
you dont need to check the socre in update loop, you just need to check if when you updating the score btw
Swap the two operands of >=
ohhhhh
I find it more legible for the thing that changes to be first in the condition. Like if (null == something) is really ugly to me
the order is different...
how do I reweight this point depending on the camera position, I can't figure it out
I don't know what i'm doing ive just barely scraped this all together π«‘
For such a "high-score system" you need to check the conditions in descending order, ie
- If the score is greater than 120
- Else, if the score is greater than 90
- Else, if the score is greater than 60
- etc.
should i do like if (ThreeStarScore <= ScoreCount && ScoreCount > TwoStarScore)
no
No, take advantage of how else if works
how would i write it then
Like this ^
gotchu
lemme give it a whirl
alright that all works now
idk how im so dumb for getting the symbols wrong + having different ones ordered oppositely π
Af'noon all, I'm working on a circular gravity system and trying to add some 'falloff' but I'm struggling a bit with the Maths.
I have a gravity amount, a falloff inner radius and a falloff outer radius. (inner radius gravity should be at 100%, outer radius it should be 0%). My brain is completely failing me and can't seem to wrap my head around it. lol.
gravity is proportional to M/R^2, not so understand
Doable with a remap operation (InverseLerp + Lerp) probably. The InverseLerp operates on the physical distance you are between the two radii, and the Lerp takes that percentage to calculate the falloff
It's not 'real' gravity, it's simulated/faked. It doesn't need to be physically accurate.,
I just need a %age multiplier between the two radii.
do distance checking and apply your custom function(distance) returns force
(1-(distance-min)/(max-min))*force
force is vector btw
Pretty much what a remap does internally yes
Okay thanks fellas.
does this mean that i cant use this for Unity?
Hey guys, I have a prob here. I have this OnTriggerEnter2D on my player script. And I am getting an error saying Object reference not set to an instance of an object. But I think I have it, tried with dif ways even tho nothing works.
Is that not referencing the enemy? or should I do other way? tried algo with findobject of type instead of assiging it on the inspector.. also didnt work
you should use "other" in the parameter
oh
it is reference something in the file but not the scene
iirc you are assigning the data variable once a prefab has been instantiated so refering to data on the prefab will, of course, return null
you mean something like that? cs playerCurrentHeath =- other._enemyPrefab.data.attackDamage;
Collider does not have an _enemyPrefab member, so no
you have not even bothered to find out what is actually null, just made an assumption
Also =- is not a thing
technically valid
hmm ok
Doesn't really matter, since getting a value on a prefab instead of on what you hit, is invalid
when I instantiate my enemy an Enemey ScriptableObject controls how much damage he deals
Yes so use GetComponent() on other to find the script that has this scriptable object reference on it, then you'll be able to access the value
Excuse me guys.
I'm having problem with subscribing my Jump function with my Jump Action
I already created the Jumper Action but the code keeps telling me that I haven't created it
hmm never used that way, so I can use GetComponent() inside the onTriggerEnter2d? crazy
You can use GetComponent on any variable of type GameObject, or Component (which Collider2D inherits from), so you can use that on other to find a script on what you just hit
Amazing, thank you very much !
Did like that and worked, thank you !! cs _enemyPrefab = other.GetComponent<Enemy>();
Yep, though it's not a prefab you're getting, it's the script on the prefab instance (the copy of the prefab in the scene)
So there is no =- ? so I should do what? like that? cs playerCurrentHeath = playerCurrentHeath - _enemyPrefab.data.attackDamage;
-=, not =-
if I use -= i get error
a -= b is the shorthand for a = a - b
Oh my mistake I am getting no error, thank you
there is not =- operator but =- (or =+, =*) can be valid or exists in source code
eg int x=-1
private void FixedUpdate()
{
rigidBody2D.velocity = inputVector * speed;
}
private void GetInputVector(Vector2 inputVector)
{
this.inputVector = inputVector;
this.inputVector.Normalize();
}
Since i receive the movement input from an event how do i reset the input vector so it doesnt moves forever? should i make an event for when i stop pressing movement input?
I copied my project onto an USB drive and moved to another pc. On th other pc the Console is floded with Errors like this:
Why or how?
You have duplicate scripts
btw the correct way to copy between projects is to use Assets->Export on the original project and Assets->Import on the new project
Or to use source control like Git
Manage to fix it
Thanks for the tip, ill do that next time
is FixedUpdate usually direct update from Update
not sure what you mean by this?
i mean that at least at my level using Update may change character speed or fire rate but changing it to FixedUpdate doesnt have any downsides
maybe it has downsides but not ones that may happen in my program
Update doesn't "change character speed or fire rate". It's just a function that runs every frame. You might have written bad code inside it that does those things but that's not Update's fault.
!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.
Seriously don't know what's going on with my brain today, can't seem to think my way out of this.
float targetDistance = Vector3.Distance(body.position, transform.position);
targetDistance = targetDistance - innerGravityRadius;
Debug.Log(targetDistance);
//gravityMultiplier = .........
I need to get the 'gravityMultiplier' based on the targetDistance. With my current 'base' values, gravityInnerRadius is 0 and my gravityOuterRadius is at 450.
The multiplier at 0 should be 1, and 450 should be 0.
Seriously struggling to figure out the maths. π¦
float gravityMultiplier = Mathf.InverseLerp(gravityOuterRadius, gravityInnerRadius, actualDistance);```
Oh very cool. Thank you. actualDistance being the targetDistance (player)?
Distance between the outer radius and the player position
Ah sorry, brain cabbaged. Thank you.
It's because the "lower bound" of the Inverse Lerp here is the outer radius (so the outer radius gives out a percentage of 0)
does anyone know how to create a new inctance of a prefab in unity
An alternative would be to Inverse Lerp starting with the inner radius, and do one minus that to reverse the 0-1 multiplier
1 - InverseLerp(inner, outer, distanceFromInner)
thanks
Right, I get what you mean. Thanks π
whenever your on a line just hover your mouse to the left of the lines number and that little popup will show itself
then you can click on it and itll have some suggestions like that show up
idk if thats exaclty what you were asking but
I want to create a couple lists of "waypoints" to define some movement patterns, but then I want to be able to select one of these "paths" at random.
My default thought was a List of Lists of gameobjects. Is there a "standard" way of handling something like this?
an array of points first
then an array of the path, where the path contains the indices of point in the first array
it can reduce the memory usage
So same concept, just with arrays then?
list is nothing more than array, you can use list
or construct a graph
this should be much better since you can run graph algorithm on it
I'm not familiar with graphs, I'll have to look that one up, but it sounds appropriate here
I'm really sorry to bother you about this, but it's seriously annoying. what am I supposed to be assigning to 'actualDistance'? Need a break and food, but this is the last 'bit' I need to figure out. lol.
Had only the second option available before, didn't have my VS configured
Well then, you have your answer.
Also, he's probably using Resharper
struct Vertex{
public Vector3 worldPosition;
public List<int> nextPositions;//contains the indices in graph
}
Vertex[] graph;
```here you have a graph
@short hazel (Sorry for the ping, but this is really frustrating me)
What kind of inverse lerp do you have here?
!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.
I may have broken it.....lol.
gravityMultiplier = Mathf.InverseLerp(outerGravityRadius, targetDistance, actualDistance);
Yeah, it's InverseLerp(outer, inner, distanceFromOuter)
Correct
hmm, okay, well my playerdistance from outer (actualDistance) is correct and reporting correctly, but the multiplier stays at 0
Ah wait the radius distances are in world space right? In that case you should be able to just put the player position there
okay, 1 sec will give it a go before I have a tantrum. lol.
ah no, can't put the player position cause vector3
the actual distance of the player from the planet
Okay, I'm assuming the inner gravity radius (surface of the planet)
i'm not 100% sure inverselerp actually works backwards like that so you might have to do
float gravityMultiplier = 1 - Mathf.InverseLerp(gravityInnerRadius, gravityOuterRadius, actualDistance);```
Oh my god I am such a moron
I was setting my outergravitydistance variable to be how far above the innergravitydistance it was (ie 450), so the calculation didn't work because they needed the world distance.
Sorry guys, but seriously thanks for the help.
Far clip plane in the scene camera settings
You can select an object and hit F to focus on it in the scene view, this will auto adjust the clipΓ₯ing planes
I am trying to make two buttons and if you hold the button on the right the play will move until you stop holding. I tried Input.GetMouseButtonDown(0) and it won't work.
i connected the void MoveToRight function to the button
Yeah that resets the clipping planes too.
nvm i solved it
flip it
Looks like the script that makes the stuff "look at" the player is backwards
You need to multiply a vector by -1 somewhere
Last thing with this now I promise. lol.
But I'm struggling to apply the gravity multiplier to the gravity value. (max gravity = -10)
gravityMultiplier = 1-Mathf.InverseLerp(innerGravityRadius, outerGravityRadius, targetDistance);
Debug.Log("Gravity Multiplier" + gravityMultiplier);
//gravity = ..........;
No matter what I try it either goes nuts, or returns a value 1/10th that of the multiplier π
Value check: all 3 values you pass to InverseLerp are relative to the center of the body (planet)
Does the log show correct values?
Yo how do i make so if you only click on the button a function works?
Yes, it shows the correct multiplier based on the players distance to the surface of the planet.
plug it to the OnClick function
or use Ipointerclickhandler
But i want to make it so if i hold the button the function works
This is the whole thing, for reference.....
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.
ohh you mean a keyboard button
use GetKey
Gravity at the closest position (less than the inner radius) is -10, and goes to 0 the farther away you go, right?
No
mouse
GetMouse
That's correct, at the 'outeredge' the multiplier reads as 0, and on the surface it reads as 1.
At 1, the 'actual' gravity should be -10.
So you can execute the second part of the remap, which is passing the ratio you get from InverseLerp to a Lerp with the min and max gravity
grav = Lerp(minGrav, maxGrav, multiplierFromInverseLerp)
If i use GetMouseButton it reacts to when i click anywhere on the screen
i want to react only when i hold it on the button
but when i assign a public void to on click
it doesn't work when i hold it
only when i click it
Which means that for this, you do not want to do a 1 - for the InverseLerp
use event tirggers
or
you need a custom script and use Ipointerclick interface
how to use event trigers
Okay, will give it a go π Thank you again.
Okay progress, it works and matches the distance, but it's 'inverted'
Show the few lines of code where you have the two Lerps
OH! I just put the 1- back in and it works perfectly.
Ah yeah I thought you were in the reversed configuration still, where the lerp was from the max radius to the min
Aaah okay. Seriously though, both you and @wintry quarry thank you so much for the help.
Hi Guys im doing a tutorial from YT and there was a point where i needed to programm Picking up items with raycast i did exactly the same thing but it doesnt work
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class SelectionManager : MonoBehaviour
{
public static SelectionManager Instance { get; set; }
public bool onTarget;
public GameObject Interaction_info_UI;
Text interaction_text;
private void Start()
{
interaction_text = Interaction_info_UI.GetComponent<Text>();
}
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
void Update()
{
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 10))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>() && selectionTransform.GetComponent<InteractableObject>().playerInRange)
{
onTarget = true;
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
Interaction_info_UI.SetActive(true);
}
else //if there is a hit, but without an Interacable Script
{
onTarget = false;
Interaction_info_UI.SetActive(false);
}
}
else //if there is no hit at all
{
onTarget = false;
Interaction_info_UI.SetActive(false);
}
}
} ```
Could somebody help me? Im so desperate to fix this problem so if anyone could help me i would pay 10$ to fix it
Your errors mention line 32 of the script you posted. Something is null on that line, but you're trying to access it anyway, resulting in an error
a.b will fail if a is null, for example
Is there a clean way to "bake" a property?
to what?
I have something like this
but I have a class that holds a collider, and the type of that collider stays fixed.
oh wait, should I just use a virtual extension method, and add it to each instead of downcasting?
or is that a bad idea?
the main issue is PolygonCollider2D just can't do it
Static stuff can't be virtual, but you can add overloads of that method
Multiple GetColliderSkin methods, with different parameter types
is it possible that your camera is not tagged as mainCamera? Otherwise clicking on the error should show you the line
but then how does Collider2D call it cleanly?
How do i check?
I feel like my Collider2D would be taking in an arg, and then using a switch case block to downcast... again
Ah you mean you don't have the concrete type at runtime
Stick to the extension method with the switch
I have a class which has a reference to Collider2D, which I believe is abstract
well, I am wondering if there is a clean way to just directly tie it, because the class that holds a collider2D is going to keep that type of collider
but it would also be better if I could just have a virtual extension method
Is that class a MonoBehaviour? If not, you can make it generic with a type constraint
I'm pretty sure Collider2D derrives from Monobehaviour
From Component sure, but that's not the question
oh yes, the holding class derrives from MonoBehavuiour
Take some debugging steps to see what's null on the affected line. See #π»βcode-beginner message
ok
this just sounds like a really simple challenge, but idk if I can avoid going through a switch-case every time I call
make sure you have a InteractableObject component on the objects you want to click and that they have a collider. And that tutorial is kinda meh looking at the code you have posted.
You also want to put print in a bunch of places to find what conditions are true and false
Okay so making that one generic is not possible. I don't see a way of making that better with extension methods. Since these are static, making them virtual is not possible
I'd stick with the switch
Like this right
another question: can I make an extension property?
Just show line 32 of the script, if you didn't take the hint
Can't you have a float value inside your own class that acts as your colliders radius?
SelectionManager.cs
I posted my Script before
I will, but I need to very frequently read and assign to the collider during a frame
he already fixed that, he has something else now
mostly assign
They figured out the error already
What? Where
It was the camera not tagged as MainCamera
Well it doesnt show the error but it still doesnt work
and its still in that code
Ah ok, they didn't explicitly say that was the issue lol
picking up the items and the name getting displayed still doesnt work
as the other comment said, use Debug.Log("some text"); to figure out what code isn't getting called
yeah doing that rn
So i did debuging like this Here 3 and Here 4 where called but 1 and 2 wasn't
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class SelectionManager : MonoBehaviour
{
public static SelectionManager Instance { get; set; }
public bool onTarget;
public GameObject Interaction_info_UI;
Text interaction_text;
private void Start()
{
interaction_text = Interaction_info_UI.GetComponent<Text>();
Debug.Log("Here 1");
}
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
void Update()
{
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 10))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>() && selectionTransform.GetComponent<InteractableObject>().playerInRange)
{
onTarget = true;
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
Interaction_info_UI.SetActive(true);
Debug.Log("Here 2");
}
else //if there is a hit, but without an Interacable Script
{
onTarget = false;
Interaction_info_UI.SetActive(false);
Debug.Log("Here 3");
}
}
else //if there is no hit at all
{
onTarget = false;
Interaction_info_UI.SetActive(false);
Debug.Log("Here 4");
}
}
}```
@short hazel In a similar vein, is there a smarter way than this:
You don't need to debug start. Do EVERY if in update
Especially important is right after the raycast
wdym
what do i place
in the code
There is a line that says raycast.
The line after it
That is the most important debug
No, not really. So stupid for them to have a base class and not pull the common properties up to it
if only the language had the tools to work around it
Yep, inheritance! But it's not even used here lol
That's what you get for trying to support multiple languages at once, and not even modify the stuff when all the alternative languages are dropped
Guys I need a little help
How to regenerate the json-like file for this Input system
You have auto-save enabled, so modifications are applied instantly. What's the real question here?
So I added that Jumper Action recently
After I generate this file
So when I subscribe a function to this action
This error shows up
Are you looking at the right file? Its name does not match the Input Actions Asset
I know, I named it so nothing get confused ._.
Did you originally name it Jump?
You can't rename it yourself!
The first time I added, Yes
Well you can, but only in the "Generate C# class" options
Then I changed to see if it works with different names
It won't. It will generate a new one named PlayerMovement on each save of the Input Actions Asset
Unless you modify it directly from the generation settings
Where did you change it?
Not exactly "change"
I deleted it and created a new action with a new name
Sorry to interrupt, but I'm having a bit of trouble with hitbox colliders and onTriggerEnter. I've added a box collider to my player gameObject, checked the "isTrigger" box, and did the same for my enemy. theoretically, the OnTriggerEnter method on my playerController script should activate when the two box colliders overlap (right?). However, as far as I can tell, the method seems to be getting called when the enemy's hitbox overlaps at all with the player's gameObject, rather than the collider. Is there something I'm missing here?
oh I think I've found the issue - or started to at least
it seems rather than activating on the gameobject, it's activating on the second hitbox I added to a child of the player (I used a child object to handle interactions)
I wonder if I can delete this old file and make it generate a new one ?
It already generated a new one. If you need to change its name, then do so from the Inspector
First solution that comes to mind is to reorganize my prefab hierarchy so that the two objects containing their colliders are even with each other? Since I believe Unity uses colliders from children objects as well. But rather than reorganizing my hierarchy is there not a way to just...consider the colliders separately?
Select the asset => where you ticked "Generate C# class", you'll have a field where you can type a class name
why am i getting a sharing violation on path error here https://hatebin.com/qspkbelvvn
if Here 2 is not logged but Here 3 than it means the object you clicked doesn't have the InteractableObject component or the player is not in range.
Due to bad code! What happens if an exception occurs say on line 11? Your stream is never closed, you have a dangling open stream to the file now. Trying to open another one throws this exception. You're good for a Unity and/or whole computer restart now.
And use a using statement to properly handle file access!
i see
and while you are at it, use XML or JSON to save files
using statement?
using (FileStream fs = ...)
{
// Use the stream as 'fs' variable
}
// stream automatically disposed, even if an exception occurs
okay okay
how are they better?
Whatever type of stream you use really, as long as it implements IDisposable, it should be done in a using statement to avoid memory leaks or unclosed handles
i was able to fix it thank you so much so do you have paypal?
is iDisposable always used in the filestream?
or is it something i would have to implement myself
The class implements IDisposable yes
is there any way to tell a script to ignore the collider on a GameObjects that's a child to the GameObjects storing the script (and the collider that I do want to use)? or do I just have to restructure my hierarchy so that the two GameObjects are even
You'll get a compiler error anyway if you try to put something that does not implement IDisposable into a using statement
hey how could I make a list in C# like this im new to scripting and this would help a lot!
okay thank you
public List<MyType> myList
public MyType[] myArray
Thank you!
consider using
[SerializeField] private
instead of public when possible
More flexible. More control over where they go. You can have more than one file. Just as easy. Just better in every way
You can also use BinaryWriter. Any custom file will do ya
okay ill look into it, thanks
you don't have to convert everything to string and than convert back manually
so its better for writing to the file?
I use zip files to store stuff. Especially useful if you have multiple payloads to save, System.IO.ZipArchive allows edit of a single entry without unpacking the archive and re-packing it again
Keeps everything tidy in a single file for the user, if they ever need to move it around
Basically a small file system in a single file. Lots of programs do that, Office files are ZIP files containing some XML
You can change the extension of an xlsx file to zip, and explore how it's made inside
I'm sorry to pester but can I please get a response to my question? a simple "no, you have to redo the hierarchy" would be fube I just wanna know if there's an option or a feature that I'm missing. Is there something wrong with how I'm asking my questions?
It's not clear what you mean. Are you talking about physics messages like OnTriggerEnter or OnCollisionEnter or just actual collisions and bumping things.
physics messages - specifically onTriggerEnter
Put the script on the child and send the info up to the parent
If you want the other way. Then not really. A rigidbody will treat all child colliders as one compound collider
the issue I'm having is that I'm trying to have the player respond to the enemy when the enemy collides with a small hitbox on the player (functionality that I execute in OnTriggerEnter), but the functionality is getting activated on a larger trigger that I have as a component on a child to the player GameObject
This answers it, thank you.
will the child object (soon to be a sibling) need it's own rigidbody?
If you want it to react to physics yes.
it doesn't use any physics or anything - just checks whether the player is in range of interactable objects
If it is a trigger collider, it just needs one of the colliding objects to have a rigidbody. So either THAT would have the rigidbody, or the thing hitting it needs one
You can also check out spatial queries though. Like OverlapSphere or raycasts or CheckBox (there are a bunch)
unfortunately the enemies do not have a rigidbody (they're ghosts so I'm using that as an excuse to not have them manage physics or pathfinding), so I suppose that means I need to add a rigidbody
I may check out those other options, but I'd rather avoid reworking the whole system if I can avoid it
thank you
Im trying to save character information to playerprefs (which it does according to Debug.Log), then load it (which it again does), and then update the ui with loaded data (which it does) but apparently every stat is just "0" instead of the value that was saved from the last session. anyone willing to look at my script and tell me where i went wrong?
var NormalizedDirection = Direction.normalized;
// Set the velocity
playercharacter.velocity = NormalizedDirection * speed;
Am I able to multiply
var NormalizedDirection = Direction.normalized;
by something so that the velocity is realitive instead of being world space?
I think rather than multiplication you'd want to add the transform of the object who's position you want the relative position to be based on
transform.InverseTransformDirection
Thats one way
Thanks
its just a text based game, i dont need to save positions, just some values
They responded to the wrong person.
And yeah, show !code. Not much we can help with without it
π 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.
omg I sure did respond to the wrong person mb
lol
Excuse me I need a little help
The Generate C# File button is gone.
why do you call gameManager.LoadCharacterData(); and not the method on the same script? NVM
It's hard to tell but maybe the problem is that you update the UI twice, once in the Load method and then in UpdateUI().
I see you have a LoadCharacterData in the gamemanager too?
Select the asset in your project files.
Are you sure you dont have an extra object that is also writing to the PlayerPrefs?
Thank you
I found it
for some reason when i imported a unity project it didnt automatically generate a csproj for me. and so when i open a script it always leads to the start screen of vs studio. anyway to generate one? (im in version 2022.1.4f1 btw)
upon finding other issues with the hierarchy restructure I decided to check out overlapCircle (I'm in 2d). but I see that it's also a collider - won't that still cause the player's rigidbody to use the overlapCircle in it's composit collider?
No, it won't be attached to the object. So it won't be included
huh ok nice, ty
wish me luck I've already spent a lot longer on this than I expected lol
"oh I just need to go in and adjust the size of the player's hitbox that'll be the easiest thing on this todo list" (<- naive and foolish)
Set your editor to VSCode in the preferences
and !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
mhm yeah thats not the problem, i just tried removing the updateui() method
already done that
yea its empty tho
https://img.sidia.net/ZEyI5/wEHUpuZA88.png/raw do you have those options?
use Debug.Log(age); right after to load it to see if the problem is with playerprefs or not
i dont. how do you even get these?
yea im sure, there is nothing else writing to playerprefs
it logs with 0
After you save and stop the game (and before loading), navigate to the PlayerPrefs file and look at it
Did you install Visual Studio atleast once?
i have visual studio?
where can i locate that file?
nvm


