#archived-code-general
1 messages Ā· Page 215 of 1
how does OverlapCollider work with DefaultContactOffset?
Are you asking if defaultContactOffset affects OverlapCollider?
yes
basically, if my shapes have a distance between 0 and DefaultContactOffset, does that count as overlap?
and to .Distance() ?
I assume Distance does not care about DefaultContactOffset
Good question š¤·āāļø maybe test it out?
I can't even guess if it affects physics queries or just actual collisions
do you have multiple instances of PlayerInputManager and can you show the inspector tab for that game object?
ok, it does
I have a weird problem with enemy spawning.
It works just fine in the editor and windows build but doesn't in android build.
Also, sometimes it spawns some of them right.
It always report the same spawn position on both windows and android.
OverlapCollider does give everything that DefaultContact offset.
I really wish the documentation specified that, or at least allowed that to be a parameter
omg AND Distance() is ALSO modified by it!
all these casting methods do this!
If I cast Col1 with col2 behind it, with a distance < 2 * DefaultContactOffset, it registers the hit with zero distance
and the distance is so strange
With DefaultContactOffset = 0.1, cast col1 into col2, where actual distance = 0.2 (2x offset), then it registers a raycasthit with = 0.015
the exact distance for distance = 0 is 0.185. Q: What and why lmao
I don't understand why it's not even 2x DefaultContactOffset
ok, so the last question I think I need answered is why Cast gives a RayCastHit with distance that is not exactly off by 2x DefaultContactOffset. like, where is that 0.015 comming from?
š 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.
in the purest sense, a FSM is basically an enum, and whatever you do to change it
how would i go about rotating a ui object towards the mouse position? the code for rotating a gameobject towards the mouse doesnt apply for ui objects, and i cant seem to find anything about it
Pretty sure you can just change the recttransform's Z angle to face towards Input.mousePosition
Setting transform.up to the direction towards the mouse should work too
nah because its a UI object and input.mouseposition would get the mouse in world space not ui space
Yeah you gotta do some conversions
is there not a variable for mouse position in ui space?
Not that I know of
https://docs.unity3d.com/ScriptReference/Input-mousePosition.html
it is in pixel coords
Pretty sure you have to use https://docs.unity3d.com/ScriptReference/RectTransformUtility.html for the screenspace -> UI space conversion or vice versa
This?
Nice
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i cant find anything i can understandabout the purpose of W from quaternion
if i do stuff to W from quaternion, it completly gets bugged
couldnt understand neither from videos, neither from articles
this makes no sense to me
same
you shouldnt be manually modifying the components of a quaternion, what is this for?
if DefaultContactOffset = 0.001, then casts can only generate RayCastHit2D where distance = 0 from shapes overlapping
if i change any of the W from quaternion to always 0, it completly bugs
SmoothCameraValues = Quaternion.SlerpUnclamped(Quaternion.Euler(Camera.main.transform.eulerAngles.x, Camera.main.transform.eulerAngles.y,0), Quaternion.Euler(MouseLookEuler.x, MouseLookEuler.y, MouseLookEuler.z), CameraDelay*Time.deltaTime);
Camera.main.transform.rotation = new Quaternion(SmoothCameraValues.x, 0, SmoothCameraValues.z, SmoothCameraValues.w);
transform.rotation = new Quaternion(0, SmoothCameraValues.y, 0, SmoothCameraValues.w);
also somehow the Y from transform.rotation doesnt work
but more about that a bit later
quaternion values are not the same as euler, what you wrote wont work at all
What you're doing is nonsensical. Don't directly modify values from a quaternion, or build your own
when working with quaternions, you don't want to manually set coordinates unless you know what you are doing. and you don't know what you are doing
so just keep it the same?
you want to make quaternions via constructors (like Quaternion.Identity, or Quaternion.Euler etc). Then operate on them
what do you mean by that?
you make a quaternion using something like Quaternion.Euler(0,0,-270f)
that is a quaternion that corresponds to a rotation for a specific Euler angle
i know that
ok, then you can do things like quaternion1 * quaternion 2
you should not go in and try to change the guts of a quaternion
Quaternion.RotateTowards is also useful
Quaternion has a bunch of methods to modify quaternions
also please cache some of those values, those lines you wrote are incredibly long. the commented one doesnt fit in your screenshot even
myQuaternion = new Quaternion(calculatedX, calculatedY, calculatedZ, calculatedW) is definitely NOT a constructor you should use unless you deeply understand quaternions
do you understand?
the commented one is older attempt which i didnt deleted yet
this one yes
still, you would improve readability by quite a bit by even just caching the camera.main.transform at the beginning of that if statement
please my eyes
i have a weird habit of writting a very long line
if i saw this in a code review, you're getting a talking to
I fixed the indent š
i made this in another programming language and it's all in one line
VForce = vec(SpeedVector:x() * cos(Duplicated:angles():yaw())*cos(Duplicated:angles():pitch()) - SpeedVector:y() * sin(Duplicated:angles():yaw())*cos(Duplicated:angles():pitch()) + SpeedVector:z() * sin(Duplicated:angles():pitch()),SpeedVector:x() * sin(Duplicated:angles():yaw()) * cos(Duplicated:angles():pitch()) + SpeedVector:y() * cos(Duplicated:angles():yaw()) * cos(Duplicated:angles():pitch()) - SpeedVector:z() * sin(Duplicated:angles():yaw()) * sin(Duplicated:angles():pitch()), SpeedVector:x() * sin(Duplicated:angles():pitch()) * sin(Duplicated:angles():yaw()) - SpeedVector:y() * cos(Duplicated:angles():pitch()) * sin(Duplicated:angles():yaw()) + SpeedVector:z() * cos(Duplicated:angles():yaw()))
ok that's not a good use of this knowledge
like this is the comparison of length
i put the kind of lua code into c# file that's why some parts are red
I dont know if you're proud of that, but you really shouldnt be. This kind of style is completely unreadable to anyone who has to work with you or is trying to help
i know, someone said hyperobfuscator 3000 XD
hye guys how do you disable the same button from being clicked more than once?
when you say "button" what do you mean exactly?
like I actually mean an object with button component attached to it
also i figured out the git
lmao he had lfs enabled
disable the button in the first click
or set to interactable = false
ok after the click set intercatable to false
but then after they click on another button and come back
yea
need a way to set interactable = true
reactivate it at that point
interactButton.onClick.AddListener(delegate {
foundObject.animationPlayEvent();
}); ```
my predicament is that each of my buttons use this same script
hey so i made a save system using unity serializables, thing is, it seems to store and instance id, even though they should be serializable, what am I missing?
this means you're trying to serialize a MonoBehaviour directly
you can't do that
and would it be fine to serialize a serializable scriptable object?
I'm not sure - pretty sure that has the same problem too
You should make a class specifically for holding serializable data
hmmm.. and is it possible to serialize a reference to a scriptable object then?
not the whole object
Sure, using Addressables, or using the path for Resources.Load
okay, will look into it
thanks
and i assume that's still more costly than storing a custom uuid i made, and then getting the element with the same uuid from a list? if you understand what i mean
ok so I have no clue where and when to reactivate it cuz my problem ssems a bit tricky
two different instances of the same event listener used for the two buttons
and need a way so the last button is not hit
Any idea on what i can do? i have an object pool system for shooting, bullet tracers, hit impacts, blood etc, this is only one shot which penetrated 2 walls so 4 impact fx, the ms is almost over 0.3-0.4. i really dont know what to do. If i keep all of them active itll be an insane amount of objects active and if i keep deactivating and activating it hurts performance.
how many GameObjects are in this impact prefab?
maybe you can reduce its complexity
3, a vfx, and a shader decal we made since decals are expensive
Does it help at all if you just throw all the components on a single object?
Also what does the PlayRandomSound code look like? Seems a little slow
Hmm, I could try that Actually
private void OnEnable()
{
audioSource.clip = AudioClipExtensions.GetRandomSoundFromArray(audioClips);
audioSource.Play();
}
@leaden ice looks like you answered my question on unity forums
is there a solution though that doesn't involve forcing it to wait ad just nit being abke to ckucj
click
I don't understand what the issue is? set interactable to false when you click
set it back to true whenever whatever happens that should re-enable it
yes but then when you click on another button and come back
like its just two instances of the same handler
and AudioClipExtensions.GetRandomSoundFromArray?
interactButton.onClick.AddListener(delegate {
foundObject.animationPlayEvent();
});
```
both buttons have this attached to it
the buttons will need to reference each other so they can re-enable each other
now how can I prevent double clicking but then when you click on the other and come back be able to click again
or there needs to be a central handler that references them both
and re-enables all but the clicked one
public static AudioClip GetRandomSoundFromArray(AudioClip[] audioClipArray)
{
if (audioClipArray.Length > 0)
{
return audioClipArray[Random.Range(0, audioClipArray.Length)];
}
return null;
}
It might just be that it takes some time to load the audio clip
This could help a bit https://docs.unity3d.com/ScriptReference/AudioClip-preloadAudioData.html
But yeah seems like thats not the main thing affecting performance there
Yea, itās mainly the .setactives. But maybe packing it on one gameobject like he said and no childās would help
Okay I'm trying to use Splines, and it seems like there's not a whole lot of built-in functionality; I'm trying to get the evaluation position of a BezierKnot on a Spline, and I'm not sure how to do that. I'm a little surprised the BezierKnot doesn't already have that info within it
For instance, a BezierKnot exactly halfway through the spline would be at position 0.5 on the spline
Theres a few good spline tools on github, give it a quick search and save yourself some headache
Any recommendations?
ill check if i can find what i worked with last year
I tested a few, not sure which one i settled with and dont have access to the source anymore as i dont work at that company anymore
https://github.com/yasirkula/UnityBezierSolution i think i used this
https://github.com/methusalah/SplineMesh if you need meshes
Phenomenal, thanks a ton!
No one would be able to help you without reading through that asset documentation. And you can't expect people to spend time on that.
To answer your question, you're expecting the animator in a constructor, but it seems like they're using some sort of factory pattern to create the states.
Anyways, the first thing to check is wether you're getting any compile errors.
can anybody suggest me a good C# and Unity tutorials to get more coding knowledge? I wanna know more lol
What is āknow moreāā¦
well
idk
maybe thereās more i can learn
maybe thereās advanced c# unity tutorials idk about
idk how to explainššššæ
There's always more you can learn. But there's so much of it, you should at least have some idea about what you want to learn.
Otherwise, just open the unity/C# manual and select a random topic that you don't know about.
Code link: https://pastebin.com/fNUXPq6n
Explaination: There is no way camera can change Y because it's set to 0 all the time, but it sets to opposite of it's parent, WHY
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.
this is actually a pretty good idea
guys help 
is the camera attached to the player?
the rotation you see in the inspector is the local rotation, when you set the cameras world y-rotation to 0 but the parent is at -64 then it will show 64 in the inspector. You might want to use transform.localEulerAngles
if i have a blender object, how do i import it into unity in a way to add a script to a specific part of it
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
Hi, Im having a script that is not included in the solution by vs code for some reason, do you know any fix?
What exactly is the problem/symptoms? Why is MonoBehaviour highlighted, is that what's not included?
sorry, I this script is not recognized by other scripts in vs code
it says type or namespace not found , and monobehaviour is not green
it is usually green when the script is being able to be found by other scripts
with intellisense in vs code
this is what I get in other scripts
but namespaces are fine both scripts have the same
cant regenerate project file since that option is missing in the last unity version god knows why
is it perhaps in a different assembly?
that maybe the issue
how can I check that?
this happend when pulling the repo from a different computer
are you using assembly definitions? is it in one of unity's special folders?
they would be the asmdef files in your project
you would have to have deliberately created them. or you've added this file to an asset's folder that uses an asmdef
of course, it's entirely possible that isn't the issue. but you aren't really showing the proper context
i didnt deliberately created them
just showing that you aren't getting the desired syntax highlighting doesn't really show anything. nor does a screenshot of a compile error in another script
when I click go to symbol, this script wont appear on the box, but any other one will appear
okay so where is it
in the asset folder like every other script
show it
unity doesnt seem to identify the error , is vs code the one that doesnt recognise the script and throw that error of type or namespace not found
if the error only appears in vs code and you have in fact saved so that unity would compile it. then it's an issue with vs code. try reconfiguring it or use a real IDE
I remember years ago having this similar issue on windows with visual studio once, Im on linux now
I use scriptable objects in many places in my game. I'm using Json.NET for serialization. I gave them unique IDs and made a converter that serializes them as their ID
then I use Resources to load all assets of a certain type of scriptable object and build an ID-to-object dictionary
which I use to turn the IDs back into objects
It's actually really convenient -- I don't have to manually do that lookup. I just defined the deserialization process to be to read the ID, grab the dictionary of the relevant type, and get the object from the dictionary
so my settings file looks like this
"toggleSettingValues": [
{
"setting": "2287B3F2A40C8403FB55C03E76C90096",
"value": true
}
]
I should base64 the UUID value instead of just writing out a hex string
33% less space!
or maybe just use a binary format
solved the issue just had to add this line to assembly c sharp .csproj file
I tried the google cardboard hello app scene in unity, then exported it to android, it works as intended, but not shure why gear icon and cross button not working?
This kind of stuff should be handled automatically by your configured tools
it usually does but maybe it had an issue for some reason
But in script there is functionality for both
why are my script variables persisting after stopping/starting the game?
like if i do something like the code below w/e the value is when I stop and then start the game it increments from that value š¤·āāļø
health;
Update() {
health++
Debug.Log(health)
}
Did you turn off domain reload?
no
which is why i suggested you go through the configuration process again. the fact that you also don't have the regenerate project files button indicates that you probably need to configure it again, because it has not been removed. it just does not appear if unity is not configured to use one of its supported code editors
Can you show the full script instead of pseudo code?
in 2D, if I use Cast/BoxCast/Distance/etc, then the distance between polygon-based colliders (in the RaycastHit) is actualDistance - 2 * defaultContactOffset + 0.015
Question: Where does that 0.015 come from?
bounds "shell"
probably
bounds are not precise and stick out of whatever they encompass
something like that makes sense, but I need to know exactly where this comes from. The number is not random error: very reliably 0.01498-0.01499
is that physx?
you can read its docs to find out exactly what causes it
oh its 2d, read box2d docs
post the code where you try to change position
Heya guys,
I'm having some troubles with colliders, namely stuff getting stuck in each other.
The big cat on spawn has an animation transforming the scale be large, however sometimes stuff gets stuck inside of it. I've tried continuous/discrete collision, and never sleep for sleeping mode. I'd like for it just to push everything out of the way, but its not working. Any ideas on what I could do? 
thanks. this helps.
itās probably worth asking my ultimate question here, which is; If I cast/.Distance between colliders A and B, and get back distance X (from the output), how much does A need to be moved to be in consistent contact with B?
eg, if I cast red block to blue block, or use.Distance to get red block out of blue block. These methods tell me distance X. How far to translate red block for consistent results
thatās also what Iāve been using. but it also has that 0.015 offset from box2D
if its inherent to box2d you can only work around it
all of apis will be using it, most likely
Iām fine with that. I just need to know how much I need to move everything so collisions are generated properly with tolerances
i would just eyeball it
setup complex stress test scenario, expose the offset, tweak it until the sim is stable
since Iām now trying to take manual control with kinematic RBs instead of dynamic RBs, which will automatically eject themselves
it might be a good time to mention that Iām making a pseudo physics engine
maybe I should just put parameters and tweak themā¦
that will give you insight
MelvMay gave me insight
cast/distance all give distance until it registers contact.
linecast/raycast do not factor in defaultContactOffset (eg polygon radius) at all, and just gives the very exact value. Not necessarily where it makes contact via physics systemās metrics
ok, I have⦠another very related question now
If I want to collide and slide, how do I do this with Cast to end in good contact?
If I cast in 1, then move to contact, I get to 2 with that slide vector, which I use for my next cast.
but Iām already in contact with slope, so woulding casting in 2 not tell me I hit the wall?
I guess you could Vector3.Project the direction to the hit surface normal to get the direction of that bottom blue line
This is pretty complex stuff though
i can do the math. thatās not the issue
And then cast again along that line
i just need to be able to do that iterative second step to end in contact with wall in 3
i guess my question is: If I move to be in contact with slope, then Cast would not see the wall, just the slope, right?
the second cast
What do you mean with 'see the wall'?
red box needs to know it is stopping at the wall
so casting at 1, I get hit on slope, move to slope
you will be creating your own cast with discrete iterations
then cast from 2, in direction along slope (toward wall), but since iām touching slope, cast will say Iām touching it at slope, right?
basically. using .Cast
You can add a very small offset to mitigate that
Also if a collider overlaps another collider at the start of the cast, it wont detect it
i guess I should give a small offset, then on the final step, move by that offset, right?
thatās not my experience
and is obnoxious af
iām pretty sure cast includes anything weāre overlapping at start
as per docs and experience
I mean after you hit the slope, for the next cast add an offset to the origin. Something like the slope's normal * 0.0001
Ah is it 2D?
yes
so much much easier
and rotations all locked. because fuck that
i do not want to deal with torque and rotations etc, so this should be a pretty pureified easy case of this problem
Ok, well, I proposed my solution
ok so we give some offset in between iterations, then if we are done, we translate by that final small offset to be in intimate contact, right?
The offset is just to avoid instantly hitting a collider again when you cast again
But hmm yeah you could revert the offset after all the casts are done so you get more precision š¤
hmm, right if I end at wall, I still need intimate contact with slope belowā¦
maybe each iteration adds in the offset/skin from the previous iteration back in
0 => 1 move by x1 - f * x1
1=> 2 move by x2 + f * x1 - f * x2;
ā¦
at end, move by f * xn
f being the offset, but being fixed magnitude
does that make sense?
I guess yeah, if I read that correctly. I'm not a big maths guy, I understand written code better
Is f here the scalar for the offset?
not a code question
sorry ill redirect question to another chat
thank you @rigid island
I keep getting this every 5 seconds for like 10 times.
Why is that happening?
And how do I fix this?
This has been happening since i updated the unity hub
please send screenshots, not screen photos
looks like you have a ~lot~ of console emssages
and it's stuck in ConsoleWindow.Repaint
perhaps you just need to stop logging so much
My laptop hanged because of that small white window sorry
I'll try commenting out all the log statements
Thanks
You could also turn on Collapse
That would stack identical log entries together
If you want to show some information that changes every frame for debug purposes, consider using OnGUI
Does that display on the info on the game view window?
Yeah, it lets you draw stuff like text and sliders on the screen
It's called "immediate mode" GUI because you run code to define what shows up every frame
Oh I needed that info.. š„² i was thinking to do that for so long but I just... Didn't
.
void OnGUI()
{
if (!debugShown)
return;
if (GUILayout.Button("Serialize"))
{
Debug.Log(SaveLoad.Serialize(progression));
}
if (GUILayout.Button("Test Round Trip"))
{
var dataString = SaveLoad.Serialize(progression);
progression = SaveLoad.Deserialize(dataString);
}
}
here's a snippet from my game
It's good for making little debug interfaces
That's cool, thanks a lot!!!
GUILayout automatically arranges the elements for you; GUI has you manually position them
I was logging the speed of my car in the consol btw xD
np (:
If you have many vehicles you want to show all at once, you could do something like this
Yea I have like 16 learning through reinforcement learning for like 8 hours š
void OnGUI() {
using (var layout = new GUILayout.AreaScope(new Rect(10 + 100 * index, 10, 100, 300)))
{
GUILayout.Label("Speed: " + myspeed);
}
}
that'll place car 0 at 10,10; car 1 goes at 110,etc; etc.
I often build a single "debug controller" that everyone registers themselves with
so that it can draw one big horizontal scope and then put each debuggable thing in its own vertical scope, or whatever
hey guys i have a question
Thanks a lot mate! Really helpful
is there a way to reveal and hide public variables by checking or unchecking a box in my own custom script?
how can i implement that?
You can make pretty complex interfaces (with sufficient blood sweat and tears , at least)
You would need to make a custom editor.
Actually -- something like NaughtyAttributes can probably help here
It's an add-on that adds useful attributes for your monobehaviours
I know that one is used to hide a field if a condition is false
Sounds like what you need.
oh great
Yep, naughty has HideIf/ShowIf
I am deeply inspired by Brigador's debug menu
iirc they use DearIMGUI
it's a beaut
debugging your game can be a drag, so you might as well make it look and feel good, hah
this is also why i've spent a few hours making custom editor icons
I like IMGUI, no matter what the UIToolkit purists say
i am tired of everything being one of these two icons
I kinda wanna start learning cpp and make an app with dear imgui
Think theres a unity port for it but i dont see the point
Are there any ways of allowing an object like a plane to yaw, roll and pitch using the direction of the mouse? I've used many techniques that although work with tilting, don't work with roll, so is there an easier way to do this?
Usually when this kinda question is asked, I see the term 'PID-controller' thrown around
It's a robotics thing but applies to games too from what I understand
yaw, roll, AND pitch with just a mouse input is a tall order.
you have to bake a ton of assumptions into it.
Anything is possible of course.
yes. I worked out the math. i think your suggestion of using a normal (instead of going backwards along the direction of the cast) is better
Nice. Yeah I remember coming to that conclusion myself too
What is a PID controller?
long story short - it's how cruise control maintains a desired speed in a car, for example
through a bunch of feedback loops and inputs into the workings of the car.
So basically having a control that is able to only move up to a certain point unless a function or if statement is met.
inputs:
- current speed
- mass of the car
- engine telemetry (RPM, current gear, etc)
outputs: - gas application
- brake application
no it's a very active feedback loop of the car constantly reading its own speed and applying control inputs to achieve a specific desired outcome
Makes sense. But wouldn't this be computer power intensive?
it's not so bad
cars can do it
anyway this same principle is applied all over robotics, manufacturing, etc
anyway a PID controller would be the "how" of if you have a desired pitch/yaw/roll and want to get there in a physically realistic way, applying airplane controls (throttle, flaps, aelerons, etc)
it's not directly related to the "how to control a plane with a mouse" question
indirectly though it may be involved if you want physical realism
True.
PID effectively means you use information from past present and future
hiii!
Alright
P = present, current value.
I = integral, sum of old values
D = derivative, where it plans to go next
i dont know if there is any way to make a yield that waits until a bool is either true or false, does anyone know if there is any way?
what is WaitUnit?
It makes a lot more sense now, i'll try to make a PID-like system for this thanks.
oh
PID controllers work to try to drive a number somewhere to maintain setpoint, and sometimes, one fraction of it is left out
many PID controllers use no integral, for example. or no derivative
let me change that rq and see if it works
you want:
yield return new WaitUntil(() => !onPurpleWall);```
or:
```cs
yield return new WaitWhile(() => onPurpleWall);```
or put very little weight
the present control directly adjusts the control based on the current value
the integral control uses a sliding window to add some extra input
the differential control looks at how fast the value is changing
so if the house is cold, you turn on the heat; if the house stays cold, you turn on more heat
and why are the breaks so strange?
and if it catches on fire you stop, i guess
like (() )
lol
wdym by "breaks"?
it's a lambda
no idea what that is
() => onPurpleWall is a lambda function. It takes in 0 parameters and returns the current value of onPurpleWall.
A lmabda is just a convenient inline way to define a function that doesn't have a name
(x,y) => x + y is a method that takes two arguments and adds them
(and returns the result)
you could also do this:
void OppositeCurrentWallValue() {
return !onPurpleWall;
}
yield return new WaitUntil(OppositeCurrentWallValue);
``` but that would be more verbose
deam i suck at understanding words
Basically it's just a function without a name, that's all.
In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to...
do you want more context to see if i can somehow explain what i mean with the on purple wall
new WaitUntil(() => Time.time > 10);
new WaitUntil(Condition);
where...
bool Condition() {
return Time.time > 10;
}
a function is a variable?
these express the same idea
functions can be stored in variables but that's not directly related to the lambda thing
it's definitely related though
in that you can store a lambda in a variable
(you can also store "normal" functions in variables)
a function stored in a variable in C# is called a delegate
a function is this?
This defines a function named firstcheckpoint
Since you defined it inside a class and it is not static, I would call it an instance method.
okay i will try to give you context
is there any page i can copy paste my code for you to revise?
since discord wont take it cuz its too large
what im trying to do is a mechanic where if you touch a purple square game object with a collider that is on layer 8, your gravity scales get reduced to 0 until you leave the wall with a dash
Kinda sounds like you want OnTriggerEnter and OnTriggerExit?
yep
The purple square (wall?) would have the trigger collider
but since i want to store the gravity scale wouldnt it be better to do it in an IEnumerator?
also i think it would be a OnCollisionEnter and OncollisionExit
since its a tangible wall
How can I get on trigger enter to work for child objects that's tagged? One tagged Enemy and one tagged Head. Both child objects have colliders with is trigger and rigidbodies.
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Does their parent have a rigidbody?
We discussed this here or in code-beginner a moment ago
No , and no collider on parent
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Okay, so what isn't working with your current setup?
thats the code
I'm not getting the trigger code to execute one sec I'll provide connect
Context
it includes movement and dash and now i want to make the player stick to the wall ( i thought of removing the gravity scale for this) and since it refreshes your dash, whenever you dash out of it to just give you back the old gravity scale. idk if this idea could work or if its just inefficient and theres a better way
Put a log in the start of OnTriggerEnter to see if it gets called at all
It could get called but your if-checks fail
the Enemy and Head isn't working , Enemy will if i put the collider on the parent even without a rigidbody , but when I do the tags on the child objects it stops working
Also - at least use else if so you don't do redundant checks
Like if the tag was "Enemy", why check if it was "Head" after that
Where is the script tho?
yeah I will be changing to this when I get it working
private void OnTriggerEnter(Collider other)
{
if (damageEnemy)
{
if (other.CompareTag("Enemy") || other.CompareTag("Head"))
{
SkeletonHealthController enemyHealthController = other.GetComponent<SkeletonHealthController>();
if (enemyHealthController != null)
{
float damage = (other.CompareTag("Head")) ? RandomDamage() * 2 : RandomDamage();
enemyHealthController.DamageEnemy(damage);
Logger.Instance.LogWarning($"Hit {other.name}" + (other.CompareTag("Head") ? "'s Head" : ""));
Destroy(gameObject);
}
}
}
if (damagePlayer && other.CompareTag("Player"))
{
PlayerHealthController playerHealthController = other.GetComponent<PlayerHealthController>();
if (playerHealthController != null)
{
playerHealthController.DamagePlayer(RandomDamage());
StartCoroutine(playerHealthController.FlashDamagePanel());
}
}
if (other.CompareTag("AR Floor"))
{
Destroy(gameObject);
Logger.Instance.LogWarning($"Hit {other.name}");
}
}
The script component with OnTriggerEnter should be on the object that has the rigidbody
it is
the bullet object
Might wanna show the bullet object then
Also how do you move the bullet? š¤
I did put a log in the top of OnTriggerEnter and it is getting called ,
Are you saying that the other collisions are working, just not Enemy and Head?
Correct
I was using Enemy tag on parent , when i changed it do head shots , i moved the tags to the child{0} and child{1} objects and they dont work
Are you sure that the parent doesn't have a rigidbody
Positive
@tawny mountain This is relevant
And make sure that damageEnemy is true when you want it to be
It always true for this projectile , it the players projectile
i ficed the overlap issue with the panels but turns out it wasnt really an overlap issue
is there a way to set an object inactive when another one is active?
Oh... that was the info needed. Why delete?
this is the code im using for the finishline
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FinishLine : MonoBehaviour
{
public GameObject winPanel;
public GameObject losePanel;
private void OnTriggerEnter(Collider Col)
{
if (Col.gameObject.tag == "RealPlayer")
{
winPanel.SetActive(true);
}
if (Col.gameObject.tag == "Player")
{
losePanel.SetActive(true);
}
}
// Update is called once per frame
void Update()
{
}
}
i thought i was wrong
it tells me my script has erros/doesnt work but no errors can be present
from what i found
And do you have compiler errors? (In unity, not the ide)
no? i dont think so
ide as in script?
Integrated Development Environment.
Looks like you are using VisualStudio
This is called Simplemovement while the file is called playermovement
So that may be the issue
Your file must match the class name in most unity versions
You actually have two scripts here, seeing the tabs, maybe you swapped out their contents?
That's what I was thinking too
So... in Unity rename the file to the same as the class. And redrag it into the box
in general, you want to be careful deleting/renaming scripts outside of unity
class Test goes in a file named Test.cs, for example.
Try to follow the standard naming conventions for C# types: "PascalCase". Capitalize the first letter of each word: SimpleMovement
if you delete/rename a file within unityās editor, itās pretty smart at realizing what files connect
not so smart if you do it elsewhere
and others are right where you want filename to match class name
how do i rename the file?
Right click the file in the Project window in unity. Select rename
because if I make a file called Movement.cs, and it has PlayerMovement : Monobehaviour, and EnemyMovement: Monobehaviour, when you drag the file, Unity will not be able to tell which class is supposed to be on the gameobject

but I CAN make PlayerMovment.cs, with PlayerMovement : Monobehaviour, and define several other classes in that file. And all is ok
wait is this the issue
And then redrag the script into that box, as I said
the missing upper case M
those are two totally different names
ah ok
Rename the class for this. As it should be PascalCase
But it's up to you. Just a normal style preference
let me scan through and see any other misswording
remove the component entirely, and add it fresh
i readded it and it still gives me errors?
This will happen if you move or rename a file outside of Unity or your code editor. Unity thinks that the old script asset was deleted and that you created a new one.
that is working
so the issue is within the script itself?
That's something wrong on Unity's end.
I would just restart the editor if it's persisting.
the program?
yeah. unity had a stroke
Yes. The Unity editor.
restart it
so i need to be really careful with how i word things
computers do not try to creatively interpret what you write
ayy
More people should have teachers that do the "i'm a compiler, tell me how to make a peanut butter and jelly sandwich"
It was fun and really eye opening in like second grade when we did it.
"Get bread", ok grabs whole loaf
nevermind
These are different errors.
And , this time, they're your code's problem.
The first exception happened because the variable named rb was not assigned.
Runtime errors it looks like
The second exception happened because there is no input axis named "horizontal"
again: computers are very literal
it doesn't matter that there is an input axis called "Horizontal"
"horizontal" is not "Horizontal"
this rb?
Correct.
Yep. You have a DECLARATION there. You now need to assign it
rb can hold a Rigidbody2D
This does not mean it has a reference.
You must assign one.
what do i assing to it
The rigidbody you want to use
I assume you want the rigidbody on the player..
from your screenshot above it looks like the one on the same object as this script is probably what you want
the name of your gameobject has nothing to do with your code
i think i got it
ignore me
ok it no longer gives me errors when i play
but i fall through the ground
does the ground have a collider
it moves
is there a way to highlight a button class? There is a method Select(), but is there some tricky way to highlight it?
But does it have a collider?
the best way would be making your own button and use functions such as IPointerEnter etc.
this way you have a custom highlight method, I suppose even without mouse being on it
its a long shot, but maybe someone ran into the same issue before? I'm using socketio in unity and in editor it works perfectly, but on android build it just doesnt. Nothing happens, no errors, warnings or any info (adb logcat) - just nothing happens
Would I be correct in assuming that situations like this are caused by two colliders getting snagged on each other? And, if so, how would I go about making sure they don't get snagged?
is your character not able to move out?
how would I go about making sure they don't get snagged
that depends on how you are moving the player and checking for collisions in the first place
The movement takes the direction the player is moving and just applies a rigidbody force in that direction
However, when I supply input for it to turn AWAY from the block it's doing this
The only reason I can think of that a situation like this is happening is that the player's collider is getting snagged on another collider
since you are using physics, the colliders wont get stuck in each other in such a way. Can you show your code
Alright
Vector2 inputVector = input.Movement();
//Calculate magnitude
float magnitude = moveForce * Mathf.Clamp(inputVector.magnitude, 0, input.LockOn() == ButtonState.PRESSED ? 0.5f : 1);
//Calculate target angle
float targetAngle = Mathf.Atan2(moveVector.x, moveVector.y) * Mathf.Rad2Deg + cameraAngle;
rb.angularVelocity = Vector3.up * (Mathf.DeltaAngle(transform.eulerAngles.y, targetAngle) / Time.fixedDeltaTime) * Mathf.Deg2Rad;
//Get a movement vector
float moveAngle = transform.eulerAngles.y + (input.LockOn() == ButtonState.PRESSED ? Mathf.Atan2(inputVector.x, inputVector.y) * Mathf.Rad2Deg : 0);
Vector3 movementVector = new Vector3(Mathf.Sin(Mathf.Deg2Rad * moveAngle), 0, Mathf.Cos(Mathf.Deg2Rad * moveAngle));
//Project on a surface
if (Physics.Raycast(transform.position + cc.center, Vector3.down, cc.height / 2 + cc.radius + 0.01f, groundingMask) &&
Vector3.Angle(Vector3.up, groundHit.normal) < slopeLimit)
{
movementVector = Vector3.ProjectOnPlane(movementVector, groundHit.normal).normalized;
}
else if (Physics.Raycast(transform.position + cc.center, Vector3.down, cc.height / 2 + cc.radius + 0.01f, groundingMask))
{
movementVector = Vector3.ProjectOnPlane(Vector3.down, groundHit.normal).normalized;
}
//Set velocity
rb.velocity = movementVector * magnitude + Vector3.up * rb.velocity.y;```
It's not an exact 1 to 1, but this is the relevant code
not necessarily
show the rigidbodies on each collider
That's just it. They don't necessarily look like they're even touching
I think I have an idea of what's going wrong, though
I think it has to do with the fact that the angle technically doesn't update instantly
So the actual movement part of the code isn't working properly
wasn't sure if your rigidbody just wasn't set correctly and so you "glitched" inside of the collider
so half stuck on one side and half stuck the other
setting collision detection from discrete->continous would fix that instance (I think you have interpolate also on but not 100% about that)
And what I would need to do is use its angular velocity to "predict" where it's going to be facing by the time of the next fixed update for a proper velocity vector
this isnt using rigidbody force like you described, its directly setting velocity. I would use Debug.DrawRay to see what the result of movementVector * magnitude + Vector3.up * rb.velocity.y is visually just to make sure that the direction lines up with what you think.
Theres a lot of things that you might be able to simplify here, like do you really need angular velocity on the player? If the player is a capsule then rotating it directly wont allow it to get caught on anything. The only thing angular velocity would do is allow other physics objects to get moved when you rotate against it which is a pretty niche case. If its a part of your game mechanic then well i guess keep it.
As for calculating the movement vector, theres a ton of trig going in here when you can just rotate a vector by a quaterion.
You might wanna cache that raycast as well before the if statements, no point doing it twice for the same check
thanks, figured it out eventually
does anyone know the game doors from roblox?
or let me get a video to make it clear
I hope bots aint gonna stop me from putting imgur link
good
in this game you can see camera tilt by mouse movement, does anyone know how can i reproduce it?
I have tried do do something:
if(Mathf.Abs(MouseLookEuler.y) > MathF.Abs(MouseLookEuler.z)) // NOT FINISHED, NEED ANOTHER "OR"
{
MouseLookEuler.z = MouseLookEuler.y;
}
ZrotationEffect = Mathf.SmoothDamp(MouseLookEuler.z, 0, ref ZrotationDelay, 0.1f); // NOT REMOVED, UNUSED
GetComponent<CharacterController>().Move((MoveVector.z*transform.forward+MoveVector.x*transform.right)*MovementForce*Time.deltaTime); //irrelevant
if(TouchCamera)
{
if(LateCameraMovement)
{
SmoothCameraValues = Quaternion.SlerpUnclamped(Quaternion.Euler(MouseLookEuler.x, MouseLookEuler.y, MouseLookEuler.z), Quaternion.Euler(Camera.main.transform.eulerAngles.x, transform.localEulerAngles.y, 0), CameraDelay*Time.deltaTime); // somehow MouseLookEuler.z not going back to 0, even if swapping between mouselookeuler.z and 0 from the ()s
Camera.main.transform.localEulerAngles = new Vector3(SmoothCameraValues.eulerAngles.x, 0, SmoothCameraValues.eulerAngles.z);
transform.localEulerAngles = new Vector3(0, SmoothCameraValues.eulerAngles.y, 0);
MouseLookEuler.z = SmoothCameraValues.eulerAngles.z; //it should have been working
}
}
it shakes (z) if the Z goes to - values
hello. i have a rigged model GO (with no components, freshly instantiated), and an animation clip array. what is the simplest way to make that model play the animations in the array at runtime?
Been messing with some stuff and came across an interesting issue where my trajectory line is not taking into account the balls size. If the ball was the size of the line this would not be an issue but since the ball is thicker than the line with smaller angles the ball will collide earlier than the lines reflect point. Also I can think of other scenarios where this could be an issue as well ( line passing by another ball without colliding with it at a closer distance than the actual ball). Basically I am trying to go for a pool ball table type aiming trajectory line. I'm surprised I cant find much online about this. I have attached a gif showing what I mean. I'm not even sure if its possible to take into account the balls size. Just thinking out loud but something like add collision X amount of units from the render line or use a circle collider the size of the ball at the collision reflect point to get the reflection. Or something along those lines.
I did try changing the code to the best of my understanding (which is limited for sure) to use 2D.CircleCast but I think maybe it needs more tweaking cause the results are kind of funky but I will keep at it. I have attached the code in case anyone sees something that I may not be doing correctly or has suggestions to change. Thank you.
To be honest, you should use https://docs.unity3d.com/Manual/physics-multi-scene.html
@steady moat Thanks - I'll check it out.
Anyone know the trick to detect collision with child objects?
yo i have a collider in this 3 d game and it get turned on during animation and i have a code saying if acollison happens on this other object it get deleted but when i play the animation to swing the hammer down the object thats supposed to be deleted because of the contact does not get deleted what do i do?
If the parent has a rigidbody, then the child colliders will a script with OnCollision/OnTrigger on the parent
children object don't have a script , the colliding object has the OnTriggerEnter lodgic
So what is the issue? I never said the child objects would have a script. I said the parent would
And there are two colliding objects, so which one? The parent or the one without children?
@spring creek this is the problem , the OnTriggerEnter method in the 3rd image isn't triggering by tag , If I put a log in the OnTriggerEnter outside of the if checks it does get triggered , just seems like it can't tell the cild object tags or something
My conversation is surrounding that link i replied to above
I have a gameobject with a rigidbody and the ability to jump and I'm trying to find the apex of the jump (relative to the starting position), and to do so I use this code
//math to find the apex of the jump
-Mathf.Pow(jumpForce, 2)) / (2 * Physics2D.gravity.y * rb2d.gravityScale
//code for the jump
private void Jump() => rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce);
which is just simply (-v^2)/(2g) = d, but results in a far greater predicted max height than the object is actually capable of
Here is the rigidbody component
Your code doesnt compile...
it's a snippet
Yeah, but you have mistaken in your snippet
Which make it impossible to know if you made an error
Oh ok. The first message I saw (the one I responded to) wasn't a response to anything, so I dunno which link you mean.
And yeah, it won't tell the tags of the children. Only the object with the rigidbody.
You can check for a script on the children and do it that way, but tags just won't work in this use case
sub 30 for jumpForce, 1 for gravityscale and -9.81 for the y component of gravity
I've done it somehow , From a Udemy tutorial I paid for by gamesPlusJames .. I'll go look at it Thank you tho
You probably iterated the children and checked the tags? Like I said, it will only use the rigidbody objects tag. The rigidbody treats all child colliders as its own compound collider
You can always get references to the children. Just not from parameter object itself
Given that you have correctly put the parentheses at the end, the formula seem to be correct.
which results in a value of ~45.9 units, however when I actually have my gameobject jump, it has an apex of ~7 units from its starting height
you should just show the full line, i believe you have more calculations going on because you have a 2nd bracket here
-Mathf.Pow(jumpForce, 2))
meaning that the division is done later than it should be
maxJump.transform.localPosition = new Vector3(0, (-Mathf.Pow(jumpForce, 2)) / (2 * Physics2D.gravity.y * rb2d.gravityScale), 0);
the extra bracket is just some paranoia
You could try:
- Try to do the simulation yourself without rigidbody.
- Track the position and plot it
- Find the deltaTime and see if it correspond to what it is suppose to be
hm actually with 30 as your jump force, ~45 is the correct value
but the object falls long before it reaches an apex of 45, which is why I'm here
I can assure you that Unity does respect physics accuratly enough
So, you probably have other factor that we cannot see.
if you run the test on a completely new object with nothing else in the way, it should reach 45
same thing happened
apogee at ~7 units
can you show more of the setup then? this should be a test in a new scene
void Start()
{
Rigidbody2D rb2d = GetComponent<Rigidbody2D>();
print(transform.position.y);
rb2d.velocity = new Vector3(0, 30);
}
also @hexed pecan
I fixed it , I forgot to change the GetComponent to GetComponentInParent ... Duh me
so that does work in an entirely new scene
(well, work as expected)
apparently my object experiences an acceleration of ~60
f u n
wsp guys , why does this code not work? its giving me an error cannot convert double to float when all my variable are floats https://hastebin.com/share/aturofisuq.cpp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Your variables are doubles, not floats. A float needs to have an f after it.
thank you sorry i am tierd its 3 am still codin
oh also how cani hard cap it so you cannot go past a certain amount of damage do i use an if statment ?
Use clamp
What is going on here
if(Script.Difficulty == 1)
{
HealthManger.health -= Time.deltaTime * 1.5 * Script.Difficulty;
}
If the difficulty is 1, then you're multiplying it by 1.
Also, why use Time.deltaTime (a small value, often around .02, but changes every frame) for health damage in OnCollisionEnter? It happens only once..
oh yea sorry i exxcludeed a part of the code dificulty is divide by.01
also sorry i am teird noticed it before you said it i changed it to time.tim
DIVIDED by .01? That would make it bigger
What? How is that better lol
ye thats the point dont worry i am hard capping it at 50 damage
so the player wouldnt take more than 50 but at the start health would progresivly loose more
sofor the hard cap for dificulty easy the cap of damage is 50 for medium its 60 for hard is 65 for impssible its 70
Hi, this is the programming channel. Maybe try moving (deleting here and reposting) your message to #š»āunity-talk or #šāweb
thank you!
So I have abilities in my game that I'm loading from Json. These abilities can be learned through different means but one of them is to have them in spellbooks you can find around the game. Is the best way to handle this by loading json into a dictionary that holds the abilityData as a scriptable object then when the item drops I connect the SO w/ the created object?
How do I reset the PrefabState scene?
So if I make changes in there and I want to reset it basically, if I try using "PrefabStageUtility.OpenPrefab(AssetDatabase.GetAssetPath(prefab));" again, it doesn't remove the unsaved changes
Because of _moveDirection.y = 0f; of the current OnMove(), the landing will be disconnected if there is an input when jumping. But I can't get rid of that code. Is there a way to solve it separately?
Why can't you get rid of it? Why not set it to the current y velocity?
Because if I remove that code, the player will fly into the sky along the direction of the camera..
And the second question?
But you could get rid of that and just build a vector in the if instead of using moveDirection directly
Hi, I'm new to unity
Im currently doing a fps movement practice project
I'm wondering why many tutorials create parent item and many sub items for camera and player?
Some of them are empty and just overlaps each other, they seem to share transforms and rotation
Actually, I just found the answer to that. I realized that when I change the _rigidbody.velocity, I can use the current y value.
what is the advantage of having these sub items?
Yeah, that was my suggestion...
Thank you so much..!!
How can I stop my camera from zooming (with the scroll wheel and new input system) while scrolling over a UI element?
This may be a preference, there are many ways to build characters or any object in Unity, though using the hierarchy is a common one - if you have a parent object for example that holds a child camera, then you can move the entire player by moving the parent, and rotate the camera independently of the player - I use a similar setup where the parent is used to host the scripts that describe what that player can do, and their physics, while holding a child camera, and empty transforms that are later populated with different animation rigs, models, and features like weapons, etc - but this setup makes sense for the game im building cause I expect the player to swap characters during gameplay and want physics on the parent to affect how everything about the player moves, while having independent animations and camera affects - but in some setups, not everything needs to be attached to a GameObject, so having child objects might not make sense in more specific cases
If this is an element thats always visible, you may have to detect mouse events for it, if its a canvas or element you toggle on (for example a "pause menu"), you could make your zoom a part of an Action Map so you can toggle it, or setup a condition to ignore the scrollwheel if your zoom works by checking in Update, or maybe toggle it with a global event when your menu becomes (in)/visible
EventSystem.IsPointerOverGameObject is a quick way to do this
I fixed it, EventSystem.IsPointerOverGameObject didn't work since I have an invisible image below my UI for detecting outside clicks. What I did was just check if that object was hovered when applying mouse wheel input
Hello friends.
How can I start coroutine A and have it at some point start coroutine B and wait for B to complete its executing before continuing? Also, B should return a value for A to use.
Aside from returning values(which is not possible with coroutines), it's pretty easy. Just yield to coroutine B from A.
I don't know if a ref/out parameter is possible. If it is you can use it to return a value I guess.š¤
Excellent, cheers!
ref/out don't work with async or coroutine methods! there's a few ways to do it but an easy one is to make a completion callback like this: IEnumerator MyCoroutine(Action<MyValue> onComplete)
They want to have a value in the calling coroutine though.
If ref/out don't work, I'd rather pass a container object to hold the value.
Although, I'd rather just use async or something. If you need a coroutine to return a value, there's something wrong.
that's what i mean, a callback lets you pass a value back to the caller, javascript-style
Hi. I got a Timeline, where 2 audio Tracks exist. These 2 audio tracks have multiple clips. Based on the selected locale I want to enable and disable one of them. How can I do that ?
I know this isn't code related but i need help, i've been trying to figure out why i can't build my mobile game and keep getting this error.
thanks!
hey people im looking for some guidance i want to make a fnaf fan game and im losing my mind i want to clamp the x rotation idk if i should be using cinemachine and their clamp functions. I want to be able to set it up so further i go it goes faster to that side of the screen what is the best way to do this its making me get really confused
what is it you need exactly , this isn't very specfic
i want to make a office movement system like the original fnaf games
what that even mean?
i never played fnaf sorry
exactly what i said
okay thats fair give me a minute
FIVE NIGHTS AT FREDDY'S Full Gameplay Walkthrough / No Commentary ćFULL GAMEć4K UHD includes the full story, ending and final boss of the game. The game was played, recorded and edited by Gamerās Little Playground team. We recorded the game in 4K 60FPS on Steam PC. In short, the video includes the full game, ending and all story related scenes. ...
the best way i can explain it i know originally it was done in clickteam using a 2d image
so its just a clamped security cam or w/e
what do you have so far, and which part isn't working?
i dont even really know where to start ive had ideas but my brain is getting very overwhelmed with it rn which is why im asking for help
when that happens you start smaller, breaking down big problem into smaller manageable problems
yeah litterally what im asking is as simple as it can be
so start with the camera thing. Clamping the Y should be fairly simple
Thats litterally what im asking for help for
well havent really presented what You tried/have tho, not much we can go on here.
if i knew how to do it i wouldnt be asking for help
plenty of examples
https://www.google.com/search?channel=fenc&q=clamping+y+rotation+unity
aint it funny the first result is also someone making a fnaf game?
https://forum.unity.com/threads/clamping-y-rotation.1366650/
clamping isnt the issue its the how sould i make the camera rotate theres many ways i could do it, when im hovering over a button it moves, when i hover over trigger it moves. so thats what i need help with i need the fastest and easiest way to do it
perhaps you should explain that earlier...
sort of hard to explain when i didnt have the words to explain it
your questions aren't clear its diffcult to help
i litterally asked the most basic thing i could explain "how can i recreate a similar office movement to fnaf"
i know i have to use clamping but my problem is actually moving the camera
Theres many ways i could do it in my head but i dont actually know how to do them
you move it with the mouse idk what else "h ow to move the camera means"
and to be honest im not here to play 20 questions
when you got real coding questions holla
I cant explain it any simpler. I need to have some way of changing the rotation when the mouse is at either side of the screen idk how to do it
That is litterally what ive been asking
im unsure whether to do it by trigger boxes just decrementing / incrementing the rotation while clamped or if theres another way to do it
the sensible thing would be increasing /decreasing a value while moving the mouse, and that will rotate the cam in that direction
Seems like a design question rather than a coding question 
not really as im asking how to code the thing
Oh, I thought you were asking for what was best to do given a feature you were wanting.
no im trying to code it so its a bit more performant and just getting my knowledge of coding practice up a bit more im technically a beginnerwith doing something like this
if you're a beginner more performant is not something you should ever have to worry about
just do what works and is easiest to do
optamizations come later, and nothing here would really need be "more perfomant" aside the usuals (don't get components in update) etc.
so would a trigger box with on mouse enter event be the best way to do it
to do what interactions?
because the way the original games work is if u move to the left a bit then it will slowly go left but if u put mouse all way to left it will go a bit faster and same with the right side
thats how the original game works
but also i will have to use raycasts and collision boxes to active things like lights and for the cameras
Anyone got 3rd person camera movement script I could yoinkš ?
i made a script that is supposed to save the game on scene change. I have made an emplty game object and attached the script. but when i reload the game after a scene change everything is set back to 0 and i cant find out why.
here is my code for the GameManage script:https://hastebin.com/share/gokuyagibo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
that has more to do with value increasing more as you move mouse faster.. something the GetAxis deals with
google has them
dont ask scripts here
Unity has a free 3rd person package, unless you have a specific question about building your own
I need something simple so I could also understand it and these people not explaining it on the internet
lol what an overly complicated way to save
also stick to file not playerprefs
You should use another format like json or binary, this current solution wont be scalable and will break rather easily.
Also i dont see where you call the load function. Add debugs to see if it runs/what the array contains
If you feel the people on youtube arent explaining, you 200% wont understand another existing solution to be able to modify it
isnt json relativley bad to use because its easily editable i mean i guess your could encrypt
You got any simple good tutorial suggestion?
Forming specific questions can help with understanding, if theres something about a particular implementation you dont understand, try to search that specific thing up, and if that doesnt work, try to form a specific question about it to get pointed in the right direction
nothing to do with json
and no its not bad at all
U know people mod games like within the same week they come out right?
never said they didnt
Is there a way to find if something is making Unity compile really slowly? lately, it's been pretty bad for me
So then worrying about editing json isn't a real issue, if someone wants to mess with their own singleplayer experience, let them
i just have heard from multiple people its generally bad to use json for saving stuff
You've been told wrong unfortunately then
but im guessing thats more multiplayer stuff
they should have also said a reason when making such claims
if someone wants to edit their savefile, and they know enough to each your Json file, and actually edit it, they are going to edit their savefile regardless
MP should be server based/validated... json would be irrelevant with that
idk would havethought people with multiple degress and decades in the industry wouldnt be wrong
Anyone can be wrong
They were š¤·āāļø
Not really afaik, are you using assembly definitions already for your code?
not really
did they just say "json = bad. i will not elaborate further" or did they also say a reason
but idk if adding in some packages made it slow down
I mean sure, you get the tiniest amount more security using binary over json... but who cares. Some guy is gonna open up your game and insert Thomas the tank engine if he wants to within the same day.
Very beginner question here but, how do I change the speed of my animation as the sample button does not seem to exist in my animator window?
Well if you don't everything goes into the same assembly definition, and everything gets recompiled with every change.
That would indeed cause it to recompile very slow in a large project.
eh they're new. no worry so much
dont crosspost
Sorry just need a answer because I see other people have it and wonder if it is a version thing or just a removed feature
doesn't mean you're entitled to crosspost, you already asked in #š»ācode-beginner . be patient.
If no one answers it probably means you havent explained the problem clear
they just said its better to have information secure rather than easily editable and json is very easy to edit. Idk if they are just very anti modding of enclosed experiences tho
Is this a rules thing cuz if it is mb
everything ona client pc easily editable
Someone will make a tool to make editing the binary easy within a day
The only way to secure the data is to store it off the local system on a server
ANYTHING (including encryption, which would require the key shipped with the game) would be easy to edit
ok bro
tbf even if its not in the rules its pretty common sense
Just to add one thing before I have to go.
This is a list of things people said is slow or bad (in comparison to something or just in general):
If statements
Reverse for loop
new input system
string.contains
unity running on 1 thread
*any* while loops in update
ints
coroutines
Json
People have misconceptions all the time. If none of these were ever good, no one would use unity or c#.
In terms of security, yes someone can open it up and edit it. But they also have to know where that file is and what to edit, chances are most people wont even care to look. They'll look online first how to do it. And the people who would tell them how to do it online would also tell them how to change it if it were binary or any other format.
I see it all the time mb for pinging more than once š
i feel like all of them its specific cases where they are bad
if the game is single player it should not matter what player does with their own game
true
anyway another question I have is regarding getting the trigger boxes in my code. Do I make public variables and just assign them there or should i be using GetObject by name/type
Some of these yea I could see cases where they are bad but that's besides the point. The if statement one was also someone claiming doing a math equation was way more efficient than checking like if(num <90 or num <180), and declared if statements as slow. This also was not a junior dev
sounds like you're already jumping ahead
get the mouse look/ rotation cam working first
then move from there
dont i just have to enable the cursor and then when it enters the trigger rotate the Y of the camera
not sure I understand why you need triggers to rotate the camera ?
because im mimicking how the original game did the camera rotation
This video has been sponsored by Skillshare. Click the link to get 2 months of Skillshare Premium for FREE: https://skl.sh/techrules
Tech Rules uses the following royalty free resources: https://pastebin.com/qmUr3Wep
Additionally, the following channels were used as background footage. Go check them out!
Markiplier: https://www.youtube.com/use...
I dont see anything about triggers
I just see a mouse rotation done the same way any RTS implements cam movement from mouse
the more mouse moves towards edge screen the faster it moves
i will just use paint to explain as thats the easiest visually
I think you're the one misunderstanding how the mechanics are done
how are u so sure when u have never played the game
because I can tell what I see
the mouseX axis is still being used as the rotation Y of cam
baring in mind the game wasnt made in unity and wasnt made by a programmer
irrelevant
I mean, this is a Unity server.
im mimicking the original
So it is kinda relevant. You shouldnt ask things that are not related to Unity
have u even been reading or just reading like 1 or 2 messages
im mimicking the original which was made in clickteam in unity
well at least the office movement
And, the answer on how to do things could, and will probably vary from an engine to an other. You better off asking support for the engine you are working with than with the engine the game has been made with.
so pretty much what ive been asking the entire time
and actually technically no as the cam only moves if its on either side in the section in the middle theres no movement
this is a botched visualization of how the original game did its movement
I get quite nerdy in this video...
Music used:
Genius Wiz - Time Gem Commercial
Karl Casey @ White Bat Audio - Sunshine
Karl Casey @ White Bat Audio - Beach Bum
Reefs - Home
it was this video not the other one
I get it, but those are just the hotzones doesn't mean you should use triggers lol
but wouldnt it be the most acurate to what im trying to achieve
depends how you do it, you could just use a certain ratio away from the edges of the screen
No. It would be way more work for something you can do by simply checking the mouse position
If it were VERY complex areas, maybe. But just for this, no eh, even then, I'd still just check mousePosition. Why bring physics into it?
hmm luckly I'm on my break, Im gonna spin up Unity rq and try something
You could use a texture and sample from it for really complex shape
its really tho just a combo of Mouse position + camera clamped to certain amount @lilac scaffold
Yeah, that's a good idea too
i might need a bit of help with the code then as im unsure how to make this happen
Wouldnt that be something simular to a Deadzone/Softzone
thats exactly what it is and i did mention this in my original question
If you were in Unity, you could easily do it with Cinemachine
No code involved
well you still need to move the target with mousepos no?
all the coding i would need to do is clamp rotation right?
Probably
Maybe, there is multiple composer
I usually do my own camera composer
okay how the do i set up the zones and the mouse stuff with cinemachine
its an interesting usecase for cinemachine transpose
I never done it but its worth a try i suppose
I was just thinking Mouse.position.x > or < Screen.width - edge size or w/e
After i get this done i got to focus on the camera system and basics of AI
I noticed that Resources.FindObjectsOfTypeAll<T>() doesn't return scriptable object which weren't loaded yet... is there a method that also include them?
can't you have a serialized list where you drag & drop your SOs into?
I could also drop them in the Resources folder alternatively, but I don't want to add an additional step to the tool
no matter how many resources i look at for scriptable objects i keep struggling to use the ones i make in game but i thik its just my inexperience
You know how a POCO (plain old C class) works? Not tied to unity editor at all. just a normal class?
a scriptable object is like a POCO that lets you make files as instances
each file lets you manually edit its contents via unity inspector.
then you can just use them as inputs so gameobjects can get information out of individual scriptable objects
example:
public class EnemyData : ScriptableObject {
[field: SerializeField] public int maxHP {get; private set;}
}
public class EnemyLogic : Monobehaviour { // This component goes on an enemy
[SerializeField] private EnemyData data;
public currentHP;
private Awake() { currentHP = data.maxHP; }
}```
does this help?
okay that does make sense its so simple yet my brain just wants to over complicate it
CreateAssetMenu lets you right click in the assets panel, and there you will find a tab that says EnemySOs, and in that tab you will find Enemy Data. If you click on that, it will make a new file
that new file is a new instance of EnemyData
so I can now make a file called GoombaData.asset and KoopaData.asset
both files represent an instance of the type EnemyData
if I now edit my EnemyData class declaration, I could add a new field
public class EnemyData : ScriptableObject {
[field: SerializeField] public int maxHP {get; private set;}
[field: SerializeField] public bool turnAtLedges {get; private set;} = false;
}```
I added turnAtLedges as a bool, that defaults to false
now all the EnemyData files I already made NOW ALSO have this new field, and all of them have this value set to false
understand?
yeah that does make a lot more sense
thats pretty much what i need only question is can i speed it up a bit
well yeah, i just used a very low number
just 1 scrip, couple of lines and a cam
no cinemachine because i wouldnt know how to do this with cinemachine
ah nice u dont have to just give me code just give me pointers what to look at
alr. I did say it earlier the logic is pretty mucheasy, the hotzones the same of any RTS edge scroll technique
instead of scrolling / panning a cam , you rotate the Y
clamp for max rotation angles
so Input.mousePosition and Screen.width are your best friends here
how do I declare an extension method property?
I want to define myCollider.ForceSendLayersTrue
ive never really played or made RTS games
I haven't myself kinda lol ut one thing I can tell you thats important from game dev is learning different mechanics you combine from diff games.
You're recycling stuff at some point, you just gotta get creative to what you're putting together
the script is dumb easy tbh.
private void Update()
{
mousePos = Input.mousePosition;
var pos = Screen.width - hotzoneSize;
if ( mousePos.x > pos && mousePos.x < Screen.width )
{
rotY += rotSpeed * Time.deltaTime;
}else if (mousePos.x > 0 && mousePos.x < 0 + hotzoneSize)
{
rotY -= rotSpeed * Time.deltaTime;
}
rotY = Mathf.Clamp(rotY, -20, 20);
cam.transform.rotation = Quaternion.Euler(0, rotY, 0);
}```
ofc you should not Hardcode the clamp values or any of that. this is just a quick thing I put together on my lunch break xD
its messy because of it
but it works
you can copy it but you wont learn much, but perhaps study the code and see why it works
Yeah i mean im more interested in what my challenges for the UI specifically for Camera system will be this movement stuff was just bugging the shit out of me
this comes from lack of understanding the basics
everything feels overwhelming when we don't know
its why i hate unity tutorials on youtube il watch them try to understand them and still learn nothing
like sure the code works fine
yeah I can make a fnaf mechanics tutorial and I havent even played the game xD
I dont know how much simpler this code itself can be explained tho lol
its pretty self explanatory
i mean its not the most difficult game to understand i can pseudo code it so easily but my pitfall is just unity coding knowledge
that just comes with experience , the more you use the more you know which methods are available to you
the worst thing to do is Paralysis by Analysis tho
at lot of my game designer friends esp they spent too much time doing a "thinking tank"
laying out all the mechanics on paper but 0 code
that doesn't get you very far in terms of hands on experience to what works and what doesnt
i also think i overthink things a lot because i dont know whats already built into unity
I am also finding visual studio a bit confusing as a code editor I really need to learn shortcuts and stuff
ehh shortcuts make things a bit quicker , I have shite memory so I only know Ctrl + c + Ctrl V
so uh im not leet enough to be a shorcut daddy
I also have seen a lot of people have insane like code completion when im watching devlogs and stuff is that custom or paid addons
thats built in the editor usually esp Visual Studio Community
or Rider
VSCode has one too but its shite atm
highly recommend the first two options
I technically can use rider free as im a student
im guessing rider is just better than VS
rider fanboys say it is
I personally use VS cause it gets the job done and i dont have to pay 100 a year
V-v-vim
I don't think there is any feature VSCommunity doesn't have that rider has. I could be 100% wrong on this
from my understanding jetbrains just makes them more noticable than VS
if you need a config guide they have one here
!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
this will get code completion working and list you all the unity built in methods
Iām struggling with contacts now. I still want physics system to generate contacts and collision callbacks for me
.Overlap reports overlapping colliders if .Distance says <= 0 (with float approximate zero)
Contacts seem to only be generated if Distance is actually negative
and similarly collision callbacks
@spring creek I edited my movement script so that it only contains parts, that might be relevant to the discussion: https://hatebin.com/lqnruhysbq
i use a custom sprite animator to handle animations for the legs, those are called in FixedUpdate, see line 45 for example.
i update the collider back to its bigger size on line 9 right on the frame i become grounded
it seems, my standing animation is updated before that, thats why the player "sticks" inside the ground for a couple of frames
@misty ibex Here is my code, if you are still interested in having a look š
Does anyone have experience with manual simulation? I'm trying to figure out the right timing to be getting contacts and collision callbacks
@spring creek FixedUpdate is executed before Update. I'll try moving the UpdateCollider function in there.
Hey guys! I have a challenge that I'm facing and I'm wondering if I am going in the right direction on it.
We have an app that should be kept light weight as it'll be on mobile. We want to have certain videos or other rather heavy files that can be played at certain portions of the game. (Such as when your phone detects a certain event like you are at a certain location, a video would play for that area or something) The issue is that we need to keep things light weight so as to not have our users download multiple gigs of content that they may never need. Would Asset Streaming be the best way to go about doing something like this?
Sorry, stepped out.
FixedUpdate doesn't necessarily run before (or after) update. It tries to run at a fixed time. If update takes too long, FixedUpdate will even run multiple times between updates
Because of this (attempted) regularity, it's where all physics calcluations/manipulations should be done
I tried connecting updating the collider directly to the animations. there is still a frame of intersection, meaning, the collider is already updated, but being pushed out of the ground.
I'm thinking that inside the update collider method just grab the floor and set the bottom of the collider to that? I see you are offsetting it downwards, so knowing actually where it is may help
Just like one raycast or something
also good to know with the execution order
hm, that sounds like a good idea
hi im setting color to these cubes by this line of code and the cubes get shiny but theyre not supposed to and when i set the color of the cubes again it gets normal not shiny how can i stop them getting shiny?
and wat is offset ?
the shine i think seems to be from emission / bloom tho
You're causing bloom.
Color is allowed to go past 100% intensity when you do HDR rendering.
The bloom post-processing effect can use this to increase the amount of bloom that comes off of that object
Although, I would expect to get bloom from emission, not from just setting the base color.
Base color isn't even HDR usually.
(but maybe it's different in the built in render pipeline)
oh right they might be going over the 1,1,1 limit of color and that causes emission color?
Right, but albedo color is generally just in the 0-1 range
since a surface can't reflect...more light than it receives, you know
but 1) I forget how this works in the built in RP and 2) maybe this is an unlit shader
If the results change when you set the color again, then you must be doing something differently
If I apply the [Flags] attribute to an enum and insert such an enum into a component, Unity allows any combination of the flags to be selected, i.e. multi-select. Is there an IMGUI equivalent? I've tried EditorGUILayout.EnumPopup() but it doesn't seem to have the multi-select functionality.
Google shows a hit for EnumFlagsField
Fantastic - thanks, guys.
I figured out how to make my physics contacts to be consistent
- Give everything +edgeradius as a skin
- At start of custom simulation, give everything -edgeradius
- Cast/move/etc everything around.
- Give evertyhing +edgeradius again
- Call .Simulate so physics system makes contacts
Hi, im trying to inherit from this class:
https://docs.unity3d.com/Packages/com.unity.postprocessing@2.0/api/UnityEngine.Rendering.PostProcessing.PostProcessEffectRenderer-1.html
but my VSC says that it cant find an import for the class, and asks:
The type or namespace name 'PostProcessEffectRenderer<>' could not be found (are you missing a using directive or an assembly reference?)CS0246
i do have an asmdef file, i downloaded the PostProcessing package (which i believe this class to be part of?) and i referenced the the Unity.PostProcessing.Runtime.asmdef which i found in the downloaded package in my own asmdef.
I dont really know what im doing with these files and references, and why, and im lost.
how do i get unity to find the package that i downloaded, so i can use it in my script?`
try resolving the current error on line 2, then apply the changes to your asmdef again. after that see if it will recognize the namespace and class you are attempting to use
resolved the script errors, but it still cant find the namespace š¦
i checked in my packages folder the file of PostProcessEffectRenderer.cs and its:
namespace UnityEngine.Rendering.PostProcessing
but i cant import that namespace.
The type or namespace name 'PostProcessing' does not exist in the namespace 'UnityEngine.Rendering' (are you missing an assembly reference?)CS0234
which render pipeline are you using ?
URP i think
could someone clarify. In deep profiler, this says KinematicPhysics2D .FixedUpdate is being called 16 times in one frame? Is that right?
might want to check
URP wouldn't use the post processing package (it has its own)
well i guess that at least makes my issue obsolete lol
it is in fact URP, ill sniff into the URP post processing then, thanks š
I have a List<[,]> and I want to find the first available slot in the list of matrixes, how can I do this?
ehm does URP not allow custom PP effects? it only states the availalbe effects in its manual, but not how to make a custom one
does anyone know how to use hinge joints im trying to make a bucket with a handle but im a little stuck can anyone help?
thanks man.
this is driving me nuts, the shader itself is uber basic, but the whole boilerplate crap unity throws at me š
does DeepProfiler show Calls in calls/frame or per some amount of time?
I'm trying to figure out why my singletons have FixedUpdate listed as having 16 calls
are you trying to make Getting Over It?
no im trying to make something similar to this post
https://forum.unity.com/threads/how-can-i-make-the-players-handheld-object-swing-around-with-the-players-movement.544796/
Im trying to set it up because of what boxfriend said so i can ask a more specific question but do you know if I need two hinge joints one for the lantern and one for the arm?
depends how much movement you want really. I've done this in the past with 1 hinge joint only for the hand
oo ok im gonna set it up quickly and see if I can get it to work before asking more questions š
you know kinematic rigidbodies are not affected by outside forces like gravity, right?
in JsonUtility, is there a way to just write the one serializable field of that class instead of wrapping it in an object?
Yeah i just threw one onto my rb on and its working a lot better! do you know of a way that I can make the Rb move when the player flicks their mouse though?
Hey guys, i'm completely new to Unity/C#, with very little Front end development knowledge and i was wondering if i should learn C#, or at least the basics before starting to make games in unity, or if i should learn C# along the way of game development.
depends on what exactly you mean, but you can always add force to the rigidbody if you want to make it start swinging around
I have a game mechanic where if you spin your mouse to fast it should swing it a little bit would that be possible by tracking the mouse movements and adding addForce accordingly?
this is really all up to you and how you learn. personally i think learning c# outside of a unity context first leads to a better understanding of how the language works and how to use it in unity once you start learning the engine. but some people prefer to learn both at the same time (and there are some courses that teach that)
yeah you could do that
thanks for the help im gonna try a couple of things the kinematic trick helped me out a lot š
yes
but sometimes c# alone can get a bit boring with much logic and no bells moving
balance it out, some stuff is easier to just test/play around in a quick Console application with no need for worrying GUI and stuff
wdym the kinematic trick? i was specifically advising against making the rigidbody kinematic (that's like the whole issue with the forum post you linked). you also cannot add force on a kinematic rigidbody either
sorry i worded that poorly It helped a lot after I turned kinematic off
ah cool
Yo how do i check an objects tag that has the code attached to it
the tag can be accessed from its gameObject
how?
do you not know how to get an object's gameObject?
no i want to know how to get the tag
christ
and where did i tell you the tag can be accessed?
ok intereesting question is there a way to keep a dictionary of functions mapped to a scene. I.E. I have the following code snnippet: ``` if (Input.GetKeyDown(KeyCode.Alpha2))
{
if (_timerCoroutine != null)
StopCoroutine(_timerCoroutine);
elapsedTime = timerDuration;
}
else if (Input.GetKeyUp(KeyCode.Alpha2))
{
StartCoroutine(_timerCoroutine);
}
never mind i got it